我试着用TaskComplectionSource
使文件打开选择器异步但是有时我让我的应用程序关闭与-1返回值,有时我得到的异常,如:制作文件选择异步 - 的Windows Phone 8.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();
}
}
}
有什么奇怪的 - 这个bug在调试时很难再现。有没有人有任何想法可能是什么原因呢?
对于初学者来说,您不应该在每次调用此方法时都使用静态任务完成源。它应该是本地的方法调用。 – Servy 2014-09-10 20:29:58
你是对的 - 这显然是“代码味道”。然而,它没有什么问题,我已经提到过在我的问题中 - 它不用于此方法以外的任何地方,它不是多线程方法(picker不能从非ui线程启动),因此竞争条件不存在。 – fex 2014-09-10 20:36:47