Task.WhenAll
Learn to await multiple tasks with Task.WhenAll.
Task.WhenAll
Task.WhenAll waits for multiple Tasks to all finish. It combines many Tasks into one; when they all complete, it returns their results together. Example: await Task.WhenAll(t1, t2, t3);.
For result-bearing Tasks it returns a Task<T[]>: int[] results = await Task.WhenAll(t1, t2);. If any task throws, WhenAll throws; but the other tasks still run to completion.
WhenAll results
When you await result-bearing Tasks with WhenAll, results come back as an array. Example: Task<int> t1 = Task.FromResult(10);, Task<int> t2 = Task.FromResult(20);; then int[] arr = await Task.WhenAll(t1, t2);. Array order matches the Task order.
To sum results you can use arr.Sum() or arr[0] + arr[1]. This is the clean way to collect results from parallel work.
Exercise Sum with WhenAll
Define static Task<int> GetA() (return Task.FromResult(10);). Define static Task<int> GetB() (return Task.FromResult(20);). Make Main a static async Task Main. Await with int[] arr = await Task.WhenAll(GetA(), GetB()); and print the sum with Console.WriteLine(arr[0] + arr[1]);.
Show example solution
Task.FromResult(10) and Task.FromResult(20). Make Main static async Task Main() and write int[] arr = await Task.WhenAll(GetA(), GetB()); Console.WriteLine(arr[0] + arr[1]);
Example solution:
using System;
using System.Threading.Tasks;
class Program
{
static Task<int> GetA()
{
return Task.FromResult(10);
}
static Task<int> GetB()
{
return Task.FromResult(20);
}
static async Task Main()
{
int[] arr = await Task.WhenAll(GetA(), GetB());
Console.WriteLine(arr[0] + arr[1]);
}
}
Test yourself
-
What does Task.WhenAll do?
- Waits for multiple Tasks to all finish
- Waits for the first Task to finish
- Cancels the Tasks
- Runs the Tasks one by one
Show answer
Waits for multiple Tasks to all finish — Correct. WhenAll waits until all Tasks finish.
-
Complete the WhenAll call
await Task.____(t1, t2, t3);Show answer
await Task.WhenAll(t1, t2, t3); -
What happens if one task throws in WhenAll?
- WhenAll returns with no action
- WhenAll throws; other tasks still complete
- WhenAll cancels all tasks
- Only the faulted task's result comes back
Show answer
WhenAll throws; other tasks still complete — Correct. WhenAll throws; but other tasks still complete.