【发布时间】:2013-06-12 22:53:58
【问题描述】:
所以我有一个特殊的问题。我有一组这样的方法:
StorageFile file;
public void WriteStuff() //This implements an interface, so can't be changed to async with a task returned
{
Write();
}
async void Write()
{
await FileIO.AppendTextAsync(file, DateTime.Now + " testing!"+Environment.NewLine);
}
async void Create()
{
file=await ApplicationData.Current.LocalFolder.CreateFileAsync("test.txt", CreationCollisionOptions.OpenIfExists);
}
然后像这样实际使用它的代码:
var x=new Foo();
for(int i=0;i<1000;i++)
{
x.WriteStuff(); //can't use async/await from here. This is in a portable class library
}
每当我打电话给Test 时,我都会收到非常随机的错误。诸如 FileNotFound、AccessDenied、AccessViolation 等。
它似乎只在异步调用AppendTextAsync 多次时发生。我会想象一个异步 API 会......好吧,线程安全,但显然不是。这是真的?
另外,如何在不修改调用代码的情况下解决此问题?
【问题讨论】:
-
抱歉,您需要使用
async Task。 -
异步与线程无关。异步 API 很少是线程安全的。
标签: c# .net windows-runtime windows-store-apps async-await