avatarcodezone

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

2021

Abstract

econd task</span> <span class="hljs-keyword">await</span> Task.WhenAll(task1, task2); Console.WriteLine(<span class="hljs-string">"Both tasks have completed."</span>); }</pre></div><p id="40bd">In this example, we have two tasks, <code>task1</code> and <code>task2</code>, each simulating a delay. By using <code>Task.WhenAll</code>, 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.</p><h1 id="b6ca">Example 2: Handling Exceptions</h1><div id="9102"><pre><span class="hljs-function"><span class="hljs-keyword">async</span> Task <span class="hljs-title">Example2Async</span>()</span> { <span class="hljs-keyword">var</span> task1 = Task.Run(() => <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> InvalidOperationException(<span class="hljs-string">"Task 1 failed."</span>)); <span class="hljs-keyword">var</span> task2 = Task.Delay(<span class="hljs-number">3000</span>); <span class="hljs-keyword">try</span> { <span class="hljs-keyword">await</span> Task.WhenAll(task1, task2); } <span class="hljs-keyword">catch</span> (Exception ex) { Console.WriteLine(<span class="hljs-string">$"Exception: <span class="hljs-subst">{ex.Message}</span>"</span>); } }</pre></div><p id="d89d">In this example, <code>task1</code> intentionally throws an exception, while <code>task2</code> is a delay task. When using <code>Task.WhenAll</code>, 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.</p><h1 id="2f02">Example 3: Performing Multiple HTTP Requests</h1><div id="a8b7"><pre><span class="hljs-keyword">async</span> Task<<span class="hljs-built_in">string</span>[]> Example3Async() { <span class="hljs-keyword">var</span> httpClient = <span class="hljs-keyword">new</span> HttpClient(); <span class="hljs-keyword">var</span>

Options

url1 = <span class="hljs-string">"https://example.com/api/data1"</span>; <span class="hljs-keyword">var</span> url2 = <span class="hljs-string">"https://example.com/api/data2"</span>; <span class="hljs-keyword">var</span> task1 = httpClient.GetStringAsync(url1); <span class="hljs-keyword">var</span> task2 = httpClient.GetStringAsync(url2); <span class="hljs-keyword">var</span> results = <span class="hljs-keyword">await</span> Task.WhenAll(task1, task2); <span class="hljs-keyword">return</span> results; }</pre></div><p id="b576">In this example, we use <code>Task.WhenAll</code> to concurrently make multiple HTTP requests to different URLs. The <code>GetStringAsync</code> method returns a <code>Task<string></code>, and we use <code>Task.WhenAll</code> 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.</p><h1 id="f36c">Conclusion</h1><p id="afb1"><code>Task.WhenAll</code> 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 <code>Task.WhenAll</code> effectively, you can write efficient and responsive asynchronous code in your C# applications.</p><h1 id="9a8c">Stackademic</h1><p id="266d"><i>Thank you for reading until the end. Before you go:</i></p><ul><li><i>Please consider <b>clapping</b> and <b>following</b> the writer! 👏</i></li><li><i>Follow us on <a href="https://twitter.com/stackademichq"><b>Twitter(X)</b></a>, <a href="https://www.linkedin.com/company/stackademic"><b>LinkedIn</b></a>, and <a href="https://www.youtube.com/c/stackademic"><b>YouTube</b></a><b>.</b></i></li><li><i>Visit <a href="http://stackademic.com/"><b>Stackademic.com</b></a> to find out more about how we are democratizing free programming education around the world.</i></li></ul></article></body>

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.
Task Management Software
Async
Development
Code
Programming
Recommended from ReadMedium