StorageFolder.GetFilesAsync()冻结UWP和WinRT应用程序

时间:2017-04-24 04:54:58

标签: c# windows-runtime uwp

我正在尝试将xml配置文件从安装目录移动到本地目录。当它到达StorageFolder.GetFilesAsync()时,它会冻结应用程序并永远不会恢复。

我调用的代码是在Windows RT项目中,所以我无法在public方法中使其异步。如果我将客户端UWP app方法设置为异步调用,似乎没有任何区别。

private async void InstallButton_Click(object sender, RoutedEventArgs e)
{
    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        bool installed = FileManager.Install(StorageLocation.Local);
    });

}

public static bool Install(StorageLocation location)
{
    return InstallAsync(location).Result;
}  

private static async Task<bool> InstallAsync(StorageLocation location)
{
    try
    {
        StorageFolder destinationFolder = null;
        if (location == StorageLocation.Local)
        {
            destinationFolder = ApplicationData.Current.LocalFolder;
        }
        else if (location == StorageLocation.Roaming)
        {
            destinationFolder = ApplicationData.Current.RoamingFolder;
        }

        if (destinationFolder == null)
        {
            return false;
        }

        StorageFolder folder = Package.Current.InstalledLocation;
        if (folder == null)
        {
            return false;
        }

        // Language files are installed in a sub directory
        StorageFolder subfolder = await folder.GetFolderAsync(languageDirectory);
        if (subfolder == null)
        {
            return false;
        }

        // Get a list of files

        IReadOnlyList<StorageFile> files = await subfolder.GetFilesAsync();

        foreach (StorageFile file in files)
        {
            if (file.Name.EndsWith(".xml"))
            {
                await file.CopyAsync(destinationFolder);
            }
        }
    }
    catch (Exception)
    { }

    return IsInstalled(location);
}

1 个答案:

答案 0 :(得分:1)

要快速解决问题,请使用该方法public async并将其传递给RunAsync来电。

private async void InstallButton_Click(object sender, RoutedEventArgs e)
{
    await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
    {
        bool installed = await FileManager.InstallAsync(StorageLocation.Local);
    });
}

此外,FileManager是否会修改用户界面?如果没有,您可以在没有调度员的情况下直接等待它。

private async void InstallButton_Click(object sender, RoutedEventArgs e)
{
    bool installed = await FileManager.InstallAsync(StorageLocation.Local);
}