UWP StorageFile文件被另一个进程使用错误

3
我的应用程序数据存储在本地 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);
    }

有时候错误出现在WriteTextAsync,有时候是在ReadTextAsync。似乎没有特定出错的时间点,只是随机发生。如果有其他避免这些错误的方法,请告诉我。
1个回答

4
问题出在你的StoreJsonFile方法上。它被标记为async void,这是一种不好的做法。当你调用这个方法并且它到达第一个IO-bound 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);
}

当您调用方法时,请始终记得使用await来确保在IO操作完成后执行将继续进行,以避免竞争条件的风险。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接