我的应用程序的数据存储在本地 JSON 中。我最初将其存储为字符串应用程序设置,但这没有提供足够的空间。因此,我正在更新我的应用程序以从本地存储中的 JSON 文件读取/写入。
当用户与我的应用程序交互时,我的应用程序会在不同时间读取和写入 JSON,并且在读取或写入文件时经常遇到此错误:
System.IO.FileLoadException:“该进程无法访问该文件,因为该文件正在被另一个进程使用。”
以下是涉及到的方法:
private static async Task<StorageFile> GetOrCreateJsonFile()
{
bool test = File.Exists(ApplicationData.Current.LocalFolder.Path + @"\" + jsonFileName);
if(test)
return await ApplicationData.Current.LocalFolder.GetFileAsync(jsonFileName);
else
return await ApplicationData.Current.LocalFolder.CreateFileAsync(jsonFileName);
}
private static async void StoreJsonFile(string json)
{
StorageFile jsonFile = await GetOrCreateJsonFile();
await FileIO.WriteTextAsync(jsonFile, json);
}
private static async Task<string> GetJsonFile()
{
StorageFile jsonFile = await GetOrCreateJsonFile();
return await FileIO.ReadTextAsync(jsonFile);
}
Run Code Online (Sandbox Code Playgroud)
有时错误出现在WriteTextAsync,有时出现在ReadTextAsync。似乎没有特定的错误发生点,似乎只是随机发生。请告诉我是否有其他方法可以避免错误。
问题出在你的StoreJsonFile方法上。它被标记为async void,这是一种不好的做法。当您调用此方法并且它到达第一个 IO 绑定async调用(在本例中FileIO.WriteTextAsync)时,它将直接结束执行,而不会等待 IO 操作完成。这是一个问题,因为当您调用GetJsonFile. 此外,当已经开始执行时,写入可能不会开始,ReadTextAsync因为系统首先运行该方法。这解释了为什么您可能会在这两种方法中看到异常。
解决方案很简单——不要使用async void,而是使用async Task:
private static async Task StoreJsonFile(string json)
{
StorageFile jsonFile = await GetOrCreateJsonFile();
await FileIO.WriteTextAsync(jsonFile, json);
}
Run Code Online (Sandbox Code Playgroud)
当您调用方法时,请始终记住使用await确保 IO 操作完成后继续执行,以免出现竞争条件的风险。
| 归档时间: |
|
| 查看次数: |
1417 次 |
| 最近记录: |