Pha*_*Luc 1 c# optimization image-processing winrt-xaml
我在窗口电话8.1中写了一个函数来显示文件夹上的图像(假设我在这个文件夹中有大约60个图像).问题是函数GetThumbnailAsync()在创建流来获取bitmapImage时需要很长时间.这是我的代码
//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
}
Run Code Online (Sandbox Code Playgroud)
我是测试,发现问题是函数GetThumbnailAsync花了这么长时间.如果我有大约60张图片,则需要大约15秒来完成此功能(我在lumia 730中测试). 有没有人遇到这个问题以及如何让这段代码运行得更快?.
非常感谢您的支持
您当前正在等待file.GetThumbnailAsync每个文件,这意味着虽然该函数是为每个文件异步执行的,但它是按顺序执行的,而不是并行执行的.
尝试将每个返回的异步操作转换file.GetThumbnailAsync为a Task,然后将其存储在列表中,然后将await所有任务存储起来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
}
Run Code Online (Sandbox Code Playgroud)