【发布时间】:2014-09-12 00:59:53
【问题描述】:
我尝试使用 TaskComplectionSource 使文件打开选择器异步,但有时我会以 -1 返回值关闭我的应用程序,有时我会遇到如下异常:
[System.Runtime.InteropServices.COMException] = {System.Runtime.InteropServices.COMException (0x80004005): Unspecified error
Unspecified error
at Windows.Storage.Pickers.FileOpenPicker.PickSingleFileAndContinue()
at PhotosGraphos.Mobile.Common.StorageFileExtensions.<PickSingleFileAsyncMobile..
代码:
public static class StorageFileExtensions
{
private static TaskCompletionSource<StorageFile> PickFileTaskCompletionSource;
private static bool isPickingFileInProgress;
public static async Task<StorageFile> PickSingleFileAsyncMobile(this FileOpenPicker openPicker)
{
if (isPickingFileInProgress)
return null;
isPickingFileInProgress = true;
PickFileTaskCompletionSource = new TaskCompletionSource<StorageFile>();
var currentView = CoreApplication.GetCurrentView();
currentView.Activated += OnActivated;
openPicker.PickSingleFileAndContinue();
StorageFile pickedFile;
try
{
pickedFile = await PickFileTaskCompletionSource.Task;
}
catch (TaskCanceledException)
{
pickedFile = null;
}
finally
{
PickFileTaskCompletionSource = null;
isPickingFileInProgress = false;
}
return pickedFile;
}
private static void OnActivated(CoreApplicationView sender, IActivatedEventArgs args)
{
var continuationArgs = args as FileOpenPickerContinuationEventArgs;
sender.Activated -= OnActivated;
if (continuationArgs != null && continuationArgs.Files.Any())
{
StorageFile pickedFile = continuationArgs.Files.First();
PickFileTaskCompletionSource.SetResult(pickedFile);
}
else
{
PickFileTaskCompletionSource.SetCanceled();
}
}
}
奇怪的是——这个错误在调试时几乎不会重现。有谁知道这可能是什么原因?
【问题讨论】:
-
对于初学者来说,您不应该在每次调用此方法时都使用静态任务完成源。它应该是方法调用的本地。
-
你是对的 - 这显然是“代码气味”。但是,我在我的问题中提到过它没有任何问题 - 它没有在此方法之外的任何地方使用,它不是多线程方法(无法从非 ui 线程启动选择器),因此这里不存在竞争条件.
标签: c# windows-runtime windows-phone-8.1