我正在尝试将一些数据保存在一个文件中,但是这个文件被不同的方法多次访问,因此给了我访问被拒绝的错误。如何对以下方法应用锁定以访问文件?
代码:
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;
}