Advertisement
Intermediate C#, Asynchronous Programming

How do you run multiple asynchronous operations concurrently and wait for all of them using Task.WhenAll?

Short answer

Start each async operation WITHOUT awaiting immediately (collecting the resulting Task objects), then await Task.WhenAll(tasks) once — this runs all operations CONCURRENTLY rather than sequentially, since each one begins executing the moment it's called, not when it's awaited.

Save C# mock interview
Advertisement
AModel answer
Start each async operation WITHOUT awaiting immediately (collecting the resulting Task objects), then await Task.WhenAll(tasks) once — this runs all operations CONCURRENTLY rather than sequentially, since each one begins executing the moment it's called, not when it's awaited.
Task<string> task1 = FetchUserAsync(1);
Task<string> task2 = FetchUserAsync(2);
Task<string> task3 = FetchUserAsync(3);
string[] results = await Task.WhenAll(task1, task2, task3); // all three run concurrently
Real-world example
Fetching data for three independent API calls simultaneously instead of sequentially awaiting each one, cutting total wait time significantly.
Likely follow-ups
  • How does Task.WhenAll handle it if ONE of the tasks throws an exception while others are still running?
Related topics