Taking something that can't be done, and then doing it.

by Jiří {x2} Činčura

Waiting for all tasks, reacting on any

Published 26 Jan 2015 in Multithreading/Parallelism/Asynchronous/Concurrency

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.

1
2
3
4
5
6
7
8
9
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.