Home >Backend Development >C++ >How Can I Efficiently Await and Retrieve Results from Multiple Concurrent Tasks in C#?
Managing Concurrent Tasks and Retrieving Results in C#
A frequent challenge in C# programming involves handling multiple asynchronous tasks that need to run concurrently and return individual results. This article demonstrates an efficient approach using Task.WhenAll
.
Here's a scenario: Imagine three independent tasks: feeding a cat, selling a house, and buying a car. Each task is asynchronous and produces a unique result.
<code class="language-csharp">private async Task<Cat> FeedCat() { /* ... */ } private async Task<House> SellHouse() { /* ... */ } private async Task<Tesla> BuyCar() { /* ... */ } async Task Main() { var catTask = FeedCat(); var houseTask = SellHouse(); var carTask = BuyCar(); await Task.WhenAll(catTask, houseTask, carTask); var cat = await catTask; var house = await houseTask; var car = await carTask; }</code>
The Task.WhenAll
method initiates all three tasks concurrently. After WhenAll
completes (signaling all tasks have finished), you can safely retrieve each task's result using individual await
operations. Asynchronous methods implicitly return already-started tasks.
While using Task.Result
is possible after WhenAll
, because task completion is guaranteed, the await
approach is generally recommended for its improved readability and robustness in more complex scenarios.
The above is the detailed content of How Can I Efficiently Await and Retrieve Results from Multiple Concurrent Tasks in C#?. For more information, please follow other related articles on the PHP Chinese website!