Use asynchronous lambda parallel
A method of parallel processing collection is to use the
method with Lambda expression. However, if you want to call the asynchronous method in the Lambda expression, you will encounter some problems.
Parallel.ForEach
The problem is that created threads are only background threads, and this method will not wait for their completion. You can see this in the following example:
Parallel.ForEach
The problem is that will be 0, because the call of
<code class="language-csharp">var bag = new ConcurrentBag<object>(); Parallel.ForEach(myCollection, async item => { // 预处理 var response = await GetData(item); bag.Add(response); // 后处理 }); var count = bag.Count;</code>
count
This method is effective, but it disables the advantages of Parallel.ForEach
and requires you to perform manual abnormal treatment. async
<code class="language-csharp">var bag = new ConcurrentBag<object>(); Parallel.ForEach(myCollection, item => { // 预处理 var responseTask = GetData(item); // 注意这里去掉了await responseTask.Wait(); var response = responseTask.Result; bag.Add(response); // 后处理 }); var count = bag.Count;</code>
await
There are two ways to achieve the use of
cycle: <.> 1. Simple and parallelization
await
This method is very simple, only a few lines of code are required: Parallel.ForEach
<.> 2. Complex and parallelization
This method is more complicated, but it can better control the process of parallelization. For details, please check the Foreachasync article of Stephen Toub.The above is the detailed content of How to Properly Use `async` Lambdas with `Parallel.ForEach`?. For more information, please follow other related articles on the PHP Chinese website!