Home > Backend Development > C++ > How to Properly Use `async` Lambdas with `Parallel.ForEach`?

How to Properly Use `async` Lambdas with `Parallel.ForEach`?

Patricia Arquette
Release: 2025-02-01 03:16:08
Original
403 people have browsed it

How to Properly Use `async` Lambdas with `Parallel.ForEach`?

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

will not wait for lambda to complete. If keywords are deleted, the method is shown below:
<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>
Copy after login

count This method is effective, but it disables the advantages of Parallel.ForEach and requires you to perform manual abnormal treatment. async

How to achieve the use of asynchronous lambda paradlel.Foreach
<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>
Copy after login

await There are two ways to achieve the use of

keyword

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!

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