Assume an asynchronous API client is used, which returns Task or Task
<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>
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.
While Parallel.ForEach and Task.WaitAll both attempt to execute tasks in parallel, they have limitations.
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>
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>
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!