Executing tasks in parallel

You should almost never use the Task constructor directly. In your case that task only fires the actual task that you can’t wait for.

You can simply call DoWork and get back a task, store it in a list and wait for all the tasks to complete. Meaning:

tasks.Add(DoWork());
// ...
await Task.WhenAll(tasks);

However, async methods run synchronously until the first await on an uncompleted task is reached. If you worry about that part taking too long then use Task.Run to offload it to another ThreadPool thread and then store that task in the list:

tasks.Add(Task.Run(() => DoWork()));
// ...
await Task.WhenAll(tasks);

Leave a Comment