C# 异步加载映像例程挂起

C# 异步加载映像例程挂起,c#,microsoft-metro,async-await,loadimage,C#,Microsoft Metro,Async Await,Loadimage,我有一个Windows 8应用程序,正在尝试使用以下代码加载图像: private async Task<BitmapImage> LoadImage(IStorageFile storageFile) { System.Diagnostics.Debug.WriteLine("LoadImage started"); try { // Set the image source to the s

我有一个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;
    }
因此,这不应该是一个沙箱问题(也没有例外)


有人能给我指出正确的路径吗?

调用
Task.Wait
Task.Result
导致死锁。我详细解释了这一点

简言之,当您等待尚未完成的
任务时,默认情况下,它将捕获一个“上下文”,并使用该上下文恢复
异步
方法。在您的例子中,这是UI上下文。但是,当调用
Wait
(或
Result
)时,会阻塞UI线程,因此
async
方法无法完成


若要解决此问题,请使用
Wait
而不是
Wait
/
Result
,并尽可能地使用
configurewait(false)

您是否有调用
Task.Wait
Task.Result
调用堆栈更高的位置?是的,我有:var loadimagestask=LoadImage(currentStorageFile); loadImageTask.Wait();DisplayImage.Source=loadImageTask.Result; LoadImage started LoadImage::OpenAsync
        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;
        }