Run asynchronous tasks in parallel and collect results in .NET 4.5
Introduction:
Simultaneously executing long-running tasks and collecting their results is a common requirement in .NET applications. In .NET 4.5, with the introduction of asynchronous programming, the traditional thread-based approach has evolved. This article explores the best ways to implement parallel execution of asynchronous tasks in .NET 4.5.
Original code:
The code provided demonstrates the basic approach of using Task.Run() to launch two long-running tasks and then using Result to retrieve their results. However, this method has some limitations:
Invalid code:
An attempt to create a non-running Task
Best solution:
The best solution involves using an asynchronous version of a long-running task and leveraging the Task.WhenAll() method. An example is as follows:
<code class="language-csharp">async Task<int> LongTask1() { // ...长时间运行的任务1... return 0; } async Task<int> LongTask2() { // ...长时间运行的任务2... return 1; } // ... { Task<int> t1 = LongTask1(); Task<int> t2 = LongTask2(); await Task.WhenAll(t1,t2); //现在我们可以访问t1.Result和t2.Result }</code>
This code creates asynchronous tasks for LongTask1 and LongTask2 and then waits for them to complete using Task.WhenAll(). This allows tasks to run concurrently without blocking. Finally, the results can be accessed using t1.Result and t2.Result.
The above is the detailed content of How Can I Efficiently Run and Collect Results from Parallel Async Tasks in .NET 4.5?. For more information, please follow other related articles on the PHP Chinese website!