FileIO.AppendTextAsync在循环中使用时抛出随机异常
本文关键字:随机 异常 AppendTextAsync 循环 FileIO | 更新日期: 2023-09-27 18:17: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应该是……好吧,线程安全,但显然不是。这是真的吗?
另外,我如何在不修改调用代码的情况下解决这个问题?
如果您确实需要这样做,那么您唯一的选择是同步Wait()
以使异步方法完成(或使用Result
):
void Write()
{
FileIO.AppendTextAsync(
file, DateTime.Now + " testing!"+Environment.NewLine).Wait();
}
void Create()
{
file = ApplicationData.Current.LocalFolder.CreateFileAsync(
"test.txt", CreationCollisionOptions.OpenIfExists).Result;
}
但是这违背了异步代码的全部目的,所以你真的应该避免这样做。另外,如果你调用的代码没有正确编写,这样做会导致死锁。
不能在这里使用async/await。这是一个可移植的类库
您可以使用PCL中的async
- await
。你只需要瞄准支持它的平台,可能还会引用Microsoft.Bcl。如果你的平台不支持Async,