所以我有一个特殊的问题。我有一组这样的方法:
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 会......好吧,线程安全,但显然不是。这是真的?
另外,如何在不修改调用代码的情况下解决此问题?