[英]Reading/Writing Async Files for Universal App
我試圖在c#中讀取/寫入通用應用程序的異步文件。 當我第一次讀寫文件時,它可以工作...但是當我立即重試它時,會出現兩個錯誤:1. UnauthorizedAccess 2. OPLOCK的句柄已關閉
看來方法尚未完成,因此數據不是免費的
(在我的框架中是一個向列表添加新成員的按鈕,然后該列表應以XML數據序列化。當我重新導航至該頁面時,該XML工作表應反序列化回該列表,因為將顯示內容)
List<Immobilie> immoListe = new List<Immobilie>();
private const string FileName_ImmoObjects = "ImmoObjects.xml";
StorageFolder sFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
IStorageFile latestImmoListFile;
public Startmenue()
{
this.InitializeComponent();
immoListe.Add(new Immobilie()); // for testing creating an XML first
immoListe[0].adresse = "Foo1";
immoListe.Add(new Immobilie());
immoListe[1].adresse = "Foo2";
WriteImmoListAsync();
ReadImmoListAsync(); // These two steps working
WriteImmoListAsync(); // everything more causes error
ReadImmoListAsync();
}
public async void WriteImmoListAsync()
{
try
{
IStorageFolder folder = await sFolder.CreateFolderAsync("Saves", CreationCollisionOption.OpenIfExists);
latestImmoListFile = await folder.CreateFileAsync(FileName_ImmoObjects, CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream stream = await latestImmoListFile.OpenAsync(FileAccessMode.ReadWrite))
using (Stream outputStream = stream.AsStreamForWrite())
{
DataContractSerializer serializer = new DataContractSerializer(typeof(List<Immobilie>));
serializer.WriteObject(outputStream, immoListe);
}
}
catch (Exception e)
{
var d = new MessageDialog(e.ToString());
await d.ShowAsync();
}
}
public async void ReadImmoListAsync()
{
int i = 0;
try
{
IStorageFolder folder = await sFolder.GetFolderAsync("Saves");
i = 1;
latestImmoListFile = await folder.GetFileAsync(FileName_ImmoObjects);
i = 2;
using (IRandomAccessStream stream = await latestImmoListFile.OpenAsync(FileAccessMode.Read))
{
i = 3;
using (Stream inputStream = stream.AsStreamForRead())
{
i = 4;
DataContractSerializer deserializer = new DataContractSerializer(typeof(List<Immobilie>));
i = 5;
immoListe = (List<Immobilie>)deserializer.ReadObject(inputStream);
}
}
}
catch (Exception e)
{
var d = new MessageDialog("Fehler I = " + i + "\n" + e.ToString());
await d.ShowAsync();
}
}
那么我該怎么辦,為什么這么困難?(普通的I / O很容易實現).-
正如我在有關async
最佳實踐的MSDN文章中所描述的那樣, 您應該避免使用async void
:
public async Task WriteImmoListAsync();
public async Task ReadImmoListAsync();
一旦您的方法正確地async Task
,那么您可以await
它們:
await WriteImmoListAsync();
await ReadImmoListAsync();
await WriteImmoListAsync();
await ReadImmoListAsync();
您必須等到方法完成才能重新啟動方法。 上面的代碼試圖執行的操作是寫入文件,但是在處理過程中,它會嘗試打開文件並在第一個方法調用尚未完成時寫入文件。 您需要等待這些方法調用完成后才能再次運行它們-在此處使用await
關鍵字會有所幫助
可能是寫入/讀取文件的過程仍附加在文件上。 您可能想看看這種模式來從Microsoft讀取/寫入異步文件:
https://msdn.microsoft.com/en-ca/library/mt674879.aspx
另外,請注意,如果讀取和寫入是通過差異過程完成的,則必須使用互斥鎖。 這是有關其工作原理的很好的解釋:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.