Home > Backend Development > C++ > How Can I Efficiently Use Async/Await for Multiple Parallel Tasks in C#?

How Can I Efficiently Use Async/Await for Multiple Parallel Tasks in C#?

Susan Sarandon
Release: 2025-01-22 03:21:08
Original
155 people have browsed it

How Can I Efficiently Use Async/Await for Multiple Parallel Tasks in C#?

Efficiently use Async/Await to handle multiple tasks in C#

Scene

Assume an asynchronous API client is used, which returns Task or Task, similar to the following example:

<code class="language-csharp">static async Task DoSomething(int siteId, int postId, IBlogClient client)
{
    await client.DeletePost(siteId, postId); // 调用API客户端
    Console.WriteLine("已删除帖子 {0}.", siteId);
}</code>
Copy after login

The goal is to start multiple asynchronous tasks simultaneously and wait for them to complete. Two commonly used methods are Parallel.ForEach and Task.WaitAll.

Shortcomings of existing methods

While Parallel.ForEach and Task.WaitAll both attempt to execute tasks in parallel, they have limitations.

  • Parallel.ForEach with Wait(): Although tasks are executed concurrently, the Wait() call blocks each participating thread. So if a network call in a task takes 2 seconds, each thread remains idle during that time, reducing efficiency.
  • Task.WaitAll: Again, this method blocks the current thread until the task is completed. During this blocking period, the thread cannot handle other tasks.

Recommended method

To overcome these limitations, we recommend using Task.WhenAll, which can execute tasks asynchronously and in parallel. The following code demonstrates its usage:

<code class="language-csharp">public async Task DoWork() {

    int[] ids = new[] { 1, 2, 3, 4, 5 };
    await Task.WhenAll(ids.Select(i => DoSomething(1, i, blogClient)));
}</code>
Copy after login

In this case, since there are no follow-up operations after the task is completed, await is not needed. The following simplified code will suffice:

<code class="language-csharp">public Task DoWork() 
{
    int[] ids = new[] { 1, 2, 3, 4, 5 };
    return Task.WhenAll(ids.Select(i => DoSomething(1, i, blogClient)));
}</code>
Copy after login

For more insights and comparisons of these approaches, see the comprehensive blog post: "How and Where to Use ASP.NET Web API for Concurrent Asynchronous I/O".

The above is the detailed content of How Can I Efficiently Use Async/Await for Multiple Parallel Tasks in C#?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template