[英]FileIO.AppendTextAsync throwing random exceptions when used in a loop
所以我有一個特殊的問題。 我有一套這樣的方法:
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
-從PCL await
。 您只需要針對支持它的平台,並且如果您的平台本身不支持它,則還可以引用Microsoft.Bcl.Async。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.