问题
I write a function to show images on a folder (assume i have about 60 images in this folder) in window phone 8.1. And the problem is function GetThumbnailAsync() take so long time when i create stream to get bitmapImage. Here's my code
//getFileInPicture is function get all file in picture folder
List<StorageFile> lstPicture = await getFileInPicture();
foreach (var file in lstPicture)
{
var thumbnail = await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView,50);
var bitmapImage = new BitmapImage();
bitmapImage.DecodePixelWidth = (int)(ScreenWidth / 4);
await bitmapImage.SetSourceAsync(thumbnail);
g_listBitmapImage.Add(bitmapImage);
//g_listBitmapImage is a list of bitmapImage
}
I was test and find the problem is function GetThumbnailAsync take so long time. If i have about 60 picture it take about 15second to finish this function( i test in lumia 730). Have anybody get this problem and how to make this code run faster ?.
Thanks so much for your supports
回答1:
You are currently awaiting file.GetThumbnailAsync
for each file which means that although the function is executed asynchronously for each file, it is executed in order, not in parallel.
Try converting each async operation returned from file.GetThumbnailAsync
to a Task
and then storing those in a list and then await
all tasks using Task.WhenAll
.
List<StorageFile> lstPicture = await getFileInPicture();
List<Task<StorageItemThumbnail>> thumbnailOperations = List<Task<StorageItemThumbnail>>();
foreach (var file in lstPicture)
{
thumbnailOperations.Add(file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.PicturesView,50).AsTask());
}
// wait for all operations in parallel
await Task.WhenAll(thumbnailOperations);
foreach (var task in thumbnailOperations)
{
var thumbnail = task.Result;
var bitmapImage = new BitmapImage();
bitmapImage.DecodePixelWidth = (int)(ScreenWidth / 4);
await bitmapImage.SetSourceAsync(thumbnail);
g_listBitmapImage.Add(bitmapImage);
//g_listBitmapImage is a list of bitmapImage
}
来源:https://stackoverflow.com/questions/30547103/how-to-improve-performance-method-getthumbnailasync-in-window-phone-8-1