Skip to main content

How to Run Several Tasks at Once and Wait for All of Them with Task.WhenAll in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

await Task.WhenAll(tea, toast, egg) waits for three tasks that are already running at the same time, so the wait takes as long as the slowest one, not all three added up. It also hands back every result, in the order you passed the tasks in.

Calling an async method starts its work and gives you a Task straight away, before the work has finished. Start several, and they run at the same time. Task.WhenAll is how you wait for all of them. Microsoft's reference: Creates a task that will complete when all of the supplied tasks have completed. And on the results: The Result of the returned task will be set to an array containing all of the results of the supplied tasks in the same order as they were provided.

Syntax​

Syntax
<Type>[] <results> = await Task.WhenAll(<task1>, <task2>, <task3>);
await Task.WhenAll(<tasks>);
PartWhat it is
<task1>, <task2>, <task3>Tasks that are already running, such as the Task<T> values that calls to async methods return. An array or a list of tasks works too
await Task.WhenAll(...)Waits until every task has finished
<Type>[] <results>For Task<T> tasks, an array of their results, in the order the tasks were passed in
await Task.WhenAll(<tasks>);For tasks without a result, which are Task rather than Task<T>: it only waits

The Example​

A console app called WhenAll makes breakfast: tea that takes 3 seconds, toast that takes 2 and an egg that takes 1. It starts all three, waits for them with Task.WhenAll, and times the wait with a Stopwatch.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n WhenAll
cd WhenAll
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/WhenAll/WhenAll.csproj:
Determining projects to restore...
Restored /Users/you/source/WhenAll/WhenAll.csproj (in 42 ms).
Restore succeeded.

dotnet new console -n WhenAll creates a folder named WhenAll with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or WhenAll.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First start the three tasks:

Program.cs (start three tasks)
using System.Diagnostics;

// Start three tasks. Each call starts its task right away, so all three run at the same time.
Stopwatch watch = Stopwatch.StartNew();
Task<string> tea = MakeAsync("Tea", 3);
Task<string> toast = MakeAsync("Toast", 2);
Task<string> egg = MakeAsync("Egg", 1);

Stopwatch.StartNew() starts a timer. Each MakeAsync call starts its work and returns a Task<string> straight away, without waiting for it, so tea, toast and egg all run at the same time.

Then wait for all three:

Program.cs (wait for all of them)
// Wait for all three. The results come back in the order the tasks were passed in.
string[] breakfast = await Task.WhenAll(tea, toast, egg);
Console.WriteLine($"All done after {watch.Elapsed.TotalSeconds:F1} seconds: {string.Join(", ", breakfast)}");

await Task.WhenAll(tea, toast, egg) waits until the last of the three has finished, then gives back a string[] with the three results. watch.Elapsed.TotalSeconds:F1 prints the time since the timer started, with one decimal.

And the method that does the work:

Program.cs (the work)
// Pretends to make something that takes a few seconds, then returns its name.
static async Task<string> MakeAsync(string item, int seconds)
{
await Task.Delay(TimeSpan.FromSeconds(seconds));
Console.WriteLine($"{item} is ready after {seconds} s");
return item;
}

Task.Delay waits the given number of seconds, in place of real work such as a download.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Egg is ready after 1 s
Toast is ready after 2 s
Tea is ready after 3 s
All done after 3.0 seconds: Tea, Toast, Egg

macOS-style terminal window titled Terminal — WhenAll showing dotnet run printing Egg is ready after 1 s, Toast is ready after 2 s, Tea is ready after 3 s and All done after 3.0 seconds: Tea, Toast, Egg

The three waits add up to 6 seconds, but everything was done after 3.0 seconds, the time of the slowest task, because all three ran at the same time. The egg finished first, yet the results came back as Tea, Toast, Egg: the order of the tasks in the call, not the order they finished in.

The Complete File​

macOS-style code window titled Program.cs — WhenAll showing a Stopwatch, three MakeAsync calls for tea, toast and egg that take 3, 2 and 1 seconds, await Task.WhenAll of the three into a string array, a line that prints the elapsed seconds and the results, and the MakeAsync method that waits with Task.Delay and returns the item

Program.cs
using System.Diagnostics;

// Start three tasks. Each call starts its task right away, so all three run at the same time.
Stopwatch watch = Stopwatch.StartNew();
Task<string> tea = MakeAsync("Tea", 3);
Task<string> toast = MakeAsync("Toast", 2);
Task<string> egg = MakeAsync("Egg", 1);

// Wait for all three. The results come back in the order the tasks were passed in.
string[] breakfast = await Task.WhenAll(tea, toast, egg);
Console.WriteLine($"All done after {watch.Elapsed.TotalSeconds:F1} seconds: {string.Join(", ", breakfast)}");

// Pretends to make something that takes a few seconds, then returns its name.
static async Task<string> MakeAsync(string item, int seconds)
{
await Task.Delay(TimeSpan.FromSeconds(seconds));
Console.WriteLine($"{item} is ready after {seconds} s");
return item;
}

When a Task Throws​

This check makes the same breakfast, but the toast (1 second) and the egg (3 seconds) throw an exception, and the tea (2 seconds) finishes. It keeps the task that Task.WhenAll returns in all, so it can look inside it after the catch:

Two tasks that throw
// Toast and Egg both throw. Tea finishes normally.
Task<string> tea = MakeAsync("Tea", 2, fails: false);
Task<string> toast = MakeAsync("Toast", 1, fails: true);
Task<string> egg = MakeAsync("Egg", 3, fails: true);
Task<string[]> all = Task.WhenAll(tea, toast, egg);

try
{
string[] breakfast = await all;
}
catch (InvalidOperationException error)
{
Console.WriteLine($"await threw: {error.Message}");
}

Console.WriteLine($"Exceptions inside the WhenAll task: {all.Exception!.InnerExceptions.Count}");
foreach (Exception inner in all.Exception.InnerExceptions)
Console.WriteLine($" {inner.Message}");
Console.WriteLine($"Tea's task: {tea.Status}, result {tea.Result}");

static async Task<string> MakeAsync(string item, int seconds, bool fails)
{
await Task.Delay(TimeSpan.FromSeconds(seconds));
if (fails)
throw new InvalidOperationException($"The {item.ToLower()} burned.");
Console.WriteLine($"{item} is ready after {seconds} s");
return item;
}
Output
Tea is ready after 2 s
await threw: The toast burned.
Exceptions inside the WhenAll task: 2
The toast burned.
The egg burned.
Tea's task: RanToCompletion, result Tea

The toast failed after 1 second, but await didn't throw until the others had finished too: Tea is ready after 2 s printed before await threw, and the exception from the 3-second egg was already inside. And await threw just one of the two exceptions. Microsoft's guide: However, only one of those exceptions is propagated by the await keyword. The task in all kept both in Exception.InnerExceptions, and the tea's result was still there. The ! after all.Exception tells the compiler that Exception isn't null at that point.

Common Mistakes​

MistakeWhat happensDo this instead
Awaiting each task as soon as you start itThe waits added up: All done after 6.0 secondsStart all the tasks first, then await Task.WhenAll(...), which took 3.0 seconds
Expecting await Task.WhenAll to throw every exceptionIt threw only The toast burned., although the egg failed tooKeep the task that Task.WhenAll returns and read its Exception.InnerExceptions, which held both
Expecting the results in the order the tasks finishedThe egg finished first, but the array was Tea, Toast, EggRead each result at the position you passed its task in

FAQ​

Does Task.WhenAll start the tasks?​

No. They start when you call the async methods. A check printed Tea: started before Calling Task.WhenAll, so the work was already running. Task.WhenAll only waits.

What does Task.WhenAll do if one task fails?​

It still waits for the others, then fails too. The reference: If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks. The section above shows it with two failures.

Conclusion​

Start every task first, then await Task.WhenAll(...): the wait takes as long as the slowest task, and you get every result back in the order you passed the tasks in. If tasks throw, await throws one of the exceptions, and the task that Task.WhenAll returned holds all of them.

Additional Resources​