我有一个 Windows 8 应用程序,我尝试使用以下代码加载图像:
private async Task<BitmapImage> LoadImage(IStorageFile storageFile)
{
System.Diagnostics.Debug.WriteLine("LoadImage started");
try
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = null;
// Ensure a file was selected
if (storageFile != null)
{
System.Diagnostics.Debug.WriteLine("LoadImage::OpenAsync");
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
System.Diagnostics.Debug.WriteLine("New Bitmap");
// Set the image source to the selected bitmap
bitmapImage = new BitmapImage();
System.Diagnostics.Debug.WriteLine("Set Source");
bitmapImage.SetSource(fileStream);
}
}
return bitmapImage;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
} // End of catch
finally
{
System.Diagnostics.Debug.WriteLine("Load image finished");
}
return null;
}
当我运行代码时,它有时会起作用。但其他时候它只是挂起,我得到以下输出:
LoadImage started LoadImage::OpenAsync
Am I using storageFile.OpenAsAsync
incorrectly? My storage file is the result of a call to:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.List;
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".bmp");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
var loadImageTask = LoadImage(currentStorageFile);
loadImageTask.Wait();
DisplayImage.Source = loadImageTask.Result;
}
所以这不应该是沙箱问题(也不异常(exception))。
有人能指出我正确的道路吗?
最佳答案
调用Task.Wait
和Task.Result
正在造成僵局。我详细解释一下on my blog和 in a recent MSDN article .
简而言之,当您 await
一个Task
尚未完成,默认情况下它将捕获“上下文”并使用它来恢复 async
方法。在您的例子中,这是 UI 上下文。但是,当您调用Wait
时(或 Result
),您正在阻塞 UI 线程,因此 async
方法无法完成。
要解决此问题,请使用 await
而不是Wait
/Result
,并使用ConfigureAwait(false)
尽你所能。
关于c# - 异步 LoadImage 例程挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16250560/