gpt4 book ai didi

c# - Windows 8 C# 从多个地方访问文件时出现拒绝访问错误

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:20 24 4
gpt4 key购买 nike

我正在尝试将一些数据保存在一个文件中,但是这个文件被不同的方法多次访问,因此出现访问被拒绝的错误。如何在以下方法上应用锁定来访问文件?

代码:

public static async Task SaveDataToFileAsync<T>(string key, T value, bool roaming = false, Type[] extraTypes = null)
{
var file = roaming ? await KnownFolders.DocumentsLibrary.CreateFileAsync(key + ".xml", CreationCollisionOption.ReplaceExisting) :
await KnownFolders.DocumentsLibrary.CreateFileAsync(key + ".xml", CreationCollisionOption.ReplaceExisting);

var xml = Xml.Serialize<T>(value, extraTypes);
await FileIO.WriteTextAsync(file, xml, UnicodeEncoding.Utf8);
}

public static async Task<T> GetdataFromFileAsync<T>(string key, T defaultValue, bool roaming = false, Type[] extraTypes = null)
{
var file = roaming ? await KnownFolders.DocumentsLibrary.CreateFileAsync(key + ".xml", CreationCollisionOption.OpenIfExists) :
await KnownFolders.DocumentsLibrary.CreateFileAsync(key + ".xml", CreationCollisionOption.OpenIfExists);

var xml = await FileIO.ReadTextAsync(file, UnicodeEncoding.Utf8);
return !String.IsNullOrEmpty(xml) ? Xml.Deserialize<T>(xml, extraTypes) : defaultValue;
}

最佳答案

您可以使用 SemaphoreSlimStephen Toub's AsyncLock . AsyncLock 也可用作 part of我的 AsyncEx 库。

这是一个 AsyncLock 的例子,它的语法比 SemaphoreSlim 更自然:

private static AsyncLock mutex = new AsyncLock();
public static async Task SaveDataToFileAsync<T>(string key, T value, bool roaming = false, Type[] extraTypes = null)
{
using (await mutex.LockAsync())
{
var file = roaming ? await KnownFolders.DocumentsLibrary.CreateFileAsync(key + ".xml", CreationCollisionOption.ReplaceExisting) :
await KnownFolders.DocumentsLibrary.CreateFileAsync(key + ".xml", CreationCollisionOption.ReplaceExisting);

var xml = Xml.Serialize<T>(value, extraTypes);
await FileIO.WriteTextAsync(file, xml, UnicodeEncoding.Utf8);
}
}

关于c# - Windows 8 C# 从多个地方访问文件时出现拒绝访问错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14500820/

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