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;
}
所以它不應該是一個沙箱的問題(也沒有例外)。
任何人都可以指出我在正確的道路?
你有沒有打電話給'Task.Wait'或'Task.Result'在你的調用堆棧的某個地方? – 2013-04-27 11:52:11
是的,我有: var loadImageTask = LoadImage(currentStorageFile); loadImageTask.Wait(); DisplayImage.Source = loadImageTask.Result; – Kyle 2013-04-27 12:35:45