2013-04-27 49 views
2

我有一個Windows 8應用程序,我嘗試使用下面的代碼加載圖像:異步的LoadImage例行掛

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 

我使用storageFile.OpenAsAsync不正確?我的存儲文件是一個調用的結果:

 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; 
     } 

所以它不應該是一個沙箱的問題(也沒有例外)。

任何人都可以指出我在正確的道路?

+0

你有沒有打電話給'Task.Wait'或'Task.Result'在你的調用堆棧的某個地方? – 2013-04-27 11:52:11

+0

是的,我有: var loadImageTask = LoadImage(currentStorageFile); loadImageTask.Wait(); DisplayImage.Source = loadImageTask.Result; – Kyle 2013-04-27 12:35:45

回答

3

致電Task.WaitTask.Result正在造成死鎖。我詳細解釋了這個on my blogin a recent MSDN article

總之,當您尚未完成的await a Task默認情況下,它將捕獲一個「上下文」並使用該方法恢復方法。就你而言,這是UI上下文。但是,當您撥打Wait(或Result)時,您將阻止UI線程,因此async方法無法完成。

爲了解決這個問題,使用await代替Wait/Result,並使用ConfigureAwait(false)到處都可以。