Home > Backend Development > C++ > How Can I Efficiently Run and Collect Results from Parallel Async Tasks in .NET 4.5?

How Can I Efficiently Run and Collect Results from Parallel Async Tasks in .NET 4.5?

DDD
Release: 2025-01-13 07:16:42
Original
337 people have browsed it

How Can I Efficiently Run and Collect Results from Parallel Async Tasks in .NET 4.5?

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:

  • Sleep cannot be an asynchronous method that can wait for other methods.
  • The code is clumsy and does not take advantage of new language features.
  • Result blocking may occur when using Result, which will affect performance.

Invalid code:

An attempt to create a non-running Task by calling an asynchronous method fails because the asynchronous method starts execution immediately.

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template