gpt4 book ai didi

c# - 为通用应用程序读取/写入异步文件

转载 作者:行者123 更新时间:2023-11-30 23:24:45 25 4
gpt4 key购买 nike

我正在尝试在 C# 中为通用应用程序读取/写入异步文件。当我第一次写入和读取文件时,它可以工作......但是当我立即重试时,有两个错误:1. UnauthorizedAccess 2. Handle with the OPLOCK has been closed

似乎方法还没有完成,所以数据不是免费的

(在我的框架中有一个按钮,用于将新成员添加到列表中,然后列表将序列化为 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 文章中所述,you should avoid async void :

public async Task WriteImmoListAsync();
public async Task ReadImmoListAsync();

一旦你的方法是正确的async Task,你就可以await它们:

await WriteImmoListAsync();   
await ReadImmoListAsync();

await WriteImmoListAsync();
await ReadImmoListAsync();

关于c# - 为通用应用程序读取/写入异步文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37593580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com