I am making a resource loading code. But, there is a problem.
var toDoList = new List<Action>();
toDoList.Add(async () =>
{
await CanvasBitmap.LoadAsync(PATH1);
Console.WriteLine("Load image");
});
toDoList.Add(async () =>
{
await CanvasBitmap.LoadAsync(PATH2);
Console.WriteLine("Load image");
});
// ...
toDoList.Add(async () =>
{
await CanvasBitmap.LoadAsync(PATH100);
Console.WriteLine("Load image");
});
toDoList.Add(() =>
{
AudioSystem.Instance.Load(AUDIO_PATH1);
Console.WriteLine("Load audio");
});
toDoList.Add(() =>
{
AudioSystem.Instance.Load(AUDIO_PATH2);
Console.WriteLine("Load audio");
});
// ...
toDoList.Add(() =>
{
AudioSystem.Instance.Load(AUDIO_PATH100);
Console.WriteLine("Load audio");
});
Console.WriteLine("Parallel Load Start");
Parallel.ForEach(toDoList, toDo => {
toDo();
});
Console.WriteLine("Parallel Load End");
I want to make Parallel wait until all LoadAsync function finished. But, because of async Action delegate, I didn't wait. It shows that
Parallel Load Start
Load audio
Load audio
Load image
Load audio
Load image
...
Load audio
Parallel Load End
Load image
Load image
Load image
...
There is no method to load image synchronously because it is a part of Win2D. (= WinRT API)
I understand why all disk I/O task must be async method.
But, above code is running at not UI thread but custom thread. So, it doesn't need to run async.
You can think that Parallel is useless due to async method. But, as you can see, toDoValues has both async (Win2D), sync (Audio). Parallel is needed for loading audio file effectively.
How can I make Parallel wait until all resources are loaded?