我有一个 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 开始 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;
}
所以它不应该是沙盒问题(也不例外)。
谁能指出我正确的道路?