Using Task.WhenAll in C#: A Comprehensive Guide with Examples
In asynchronous programming with C#, managing multiple asynchronous operations efficiently is a common requirement. The Task.WhenAll method is a powerful tool for concurrently executing multiple tasks and awaiting their completion. In this comprehensive guide, we'll explore the usage of Task.WhenAll with detailed examples to help you understand how it works and when to use it effectively in your asynchronous C# code.

Understanding Task.WhenAll
Task.WhenAll is a static method provided by the Task class in C#. It allows you to execute multiple tasks concurrently and asynchronously await their completion. It accepts an array of tasks and returns a new task that completes when all the input tasks have completed or when any of them throws an exception.
The signature of Task.WhenAll is as follows:
public static Task WhenAll(params Task[] tasks);Using Task.WhenAll with Examples
Example 1: Running Tasks in Parallel
async Task Example1Async()
{
var task1 = Task.Delay(2000); // Simulate a 2-second task
var task2 = Task.Delay(3000); // Simulate a 3-second task
await Task.WhenAll(task1, task2);
Console.WriteLine("Both tasks have completed.");
}In this example, we have two tasks, task1 and task2, each simulating a delay. By using Task.WhenAll, we can await the completion of both tasks concurrently. This is useful when you have independent tasks that can run in parallel without waiting for each other.
Example 2: Handling Exceptions
async Task Example2Async()
{
var task1 = Task.Run(() => throw new InvalidOperationException("Task 1 failed."));
var task2 = Task.Delay(3000);
try
{
await Task.WhenAll(task1, task2);
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}In this example, task1 intentionally throws an exception, while task2 is a delay task. When using Task.WhenAll, if any of the input tasks throws an exception, the resulting task will also throw an exception. We catch the exception and handle it accordingly.
Example 3: Performing Multiple HTTP Requests
async Task<string[]> Example3Async()
{
var httpClient = new HttpClient();
var url1 = "https://example.com/api/data1";
var url2 = "https://example.com/api/data2";
var task1 = httpClient.GetStringAsync(url1);
var task2 = httpClient.GetStringAsync(url2);
var results = await Task.WhenAll(task1, task2);
return results;
}In this example, we use Task.WhenAll to concurrently make multiple HTTP requests to different URLs. The GetStringAsync method returns a Task<string>, and we use Task.WhenAll to wait for both requests to complete simultaneously. This is a common scenario in web applications when you need to fetch data from multiple sources concurrently.
Conclusion
Task.WhenAll is a valuable tool for managing multiple asynchronous tasks in C#. It allows you to efficiently run tasks concurrently and await their completion, making your asynchronous code more responsive and performant. By understanding how to use Task.WhenAll effectively, you can write efficient and responsive asynchronous code in your C# applications.
Stackademic
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Follow us on Twitter(X), LinkedIn, and YouTube.
- Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.
