【发布时间】:2017-09-20 15:51:49
【问题描述】:
我正在尝试将 xml 配置文件从安装目录移动到本地目录。当它到达 StorageFolder.GetFilesAsync() 时,它会冻结应用程序并且永远不会恢复。
我正在调用的代码位于 Windows RT 项目中,因此我无法在公共方法中使其异步。如果我将客户端 UWP 应用程序方法设为异步调用,似乎没有什么区别。
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);
}
【问题讨论】:
-
尝试在您的按钮点击中调用
await FileManager.InstallAsync(StorageLocation.Local);,而不是等待它。不要让异步代码同步运行 - 您也可以在 Stephen Cleary's blog 阅读有关死锁的信息。另一件事 -IsInstalled(location)是什么? - 它是另一种同步等待异步代码的方法(如.Result)? -
另一个问题 - 为什么你在 Distpatcher 上运行它?
标签: c# windows-runtime uwp