【问题标题】:UWP StorageFile file in use by another process errors另一个进程错误正在使用 UWP StorageFile 文件
【发布时间】:2018-08-22 04:31:52
【问题描述】:

我的应用程序的数据存储在本地 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 上。似乎没有发生错误的特定点,只是似乎随机发生。如果有其他方法可以避免错误,请告诉我。

【问题讨论】:

    标签: uwp storagefile


    【解决方案1】:

    问题出在您的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 操作完成后继续执行,以免出现竞争条件的风险。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-09
      • 2014-01-28
      相关资源
      最近更新 更多