I have a C# UWP solution for myself and I have defined the special manifest broadFileSystemAccess
, so I can access all files from my PC directly.
Now I'm loading a bunch of image files into memory in order to show them on a GridView
. At this task needs a lot of time, I would like to speed it up by running it parallel.
foreach (var item in someList)
{
BitmapImage bitmapImage = new BitmapImage();
StorageFile file = await StorageFile.GetFileFromPathAsync(item.ImagePath);
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
await bitmapImage.SetSourceAsync(fileStream);
}
someOtherList.Add(new someModel { ... });
};
On some other thread I found the usage of Parallel.ForEach
- but that does not support async calls. Then I saw a library called Dasync
with using Dasync.Collections
. However using this function just throws an error saying something about an interface that was marshalled for another thread that was called by the application (roughly translated), so I figured that library might not be suitable for this task either.
How would I parallelize this in a C# UWP application?
You could start all tasks and then wait for them all to complete using Task.WhenAll
:
Func<Item, Task<BitmapImage>> f = async (item) =>
{
BitmapImage bitmapImage = new BitmapImage();
StorageFile file = await StorageFile.GetFileFromPathAsync(item.ImagePath);
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
await bitmapImage.SetSourceAsync(fileStream);
}
return bitmapImage;
};
BitmapImage[] bitmapImages = await Task.WhenAll(someList.Select(f).ToArray());