Waiting for all tasks, reacting on any
About a week ago I needed to wait on all tasks to complete and also do some side processing as any completes. Sure I could wrap it using ContinueWith
or something like that, but I made it from other way around.
I called my method WhenAllOnAny
for lack of better ideas. The method ended up pretty straightforward. I’m doing WhenAny
as long as there’s at least one task still running. When one completes I fire the event.
public static async Task WhenAllOnAny(Task[] tasks, Action<Task> onAny)
{
while (tasks.Length > 0)
{
var task = await Task.WhenAny(tasks).ConfigureAwait(false);
tasks = tasks.Where(t => t != task).ToArray();
onAny(task);
}
}
It looked like a good mental training initially, but at the end it’s pretty boring. Disappointed.