VJAI
VJAI

Reputation: 32768

How can I wait till the Parallel.ForEach completes

I'm using TPL in my current project and using Parallel.Foreach to spin many threads. The Task class contains Wait() to wait till the task gets completed. Like that, how I can wait for the Parallel.ForEach to complete and then go into executing next statements?

Upvotes: 157

Views: 146253

Answers (5)

sawe
sawe

Reputation: 1151

if you are storing results from the tasks in a List, make sure to use a thread-safe data structure such as ConcurrentBag, otherwise, some results would be missing because of concurrent write issues.

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273264

You don't have to do anything special, Parallel.Foreach() will wait until all its branched tasks are complete. From the calling thread you can treat it as a single synchronous statement and for instance wrap it inside a try/catch.

Update:

The old Parallel class methods are not a good fit for async (Task based) programming. But starting with dotnet 6 we can use Parallel.ForEachAsync()

await Parallel.ForEachAsync(items, (item, cancellationToken) =>
  {
     await ... 
  });

There are a few overloads available and the 'body' method should return a ValueTask.

Upvotes: 238

Jacob
Jacob

Reputation: 27

I believe that you can use IsCompleted like follows:

if(Parallel.ForEach(files, f => ProcessFiles(f)).IsCompleted)
{
    // DO STUFF                
}         

Upvotes: -3

Oleg Boguslawski
Oleg Boguslawski

Reputation: 137

As everyone here said - you dont need to wait for it. What I can add from my experience: If you have an async body to execute and you await some async calls inside, it just ran through my code and did not wait for anything. So I just replaced the await with .Result - then it worked as intended. I couldnt find out though why is that so :/

Upvotes: 11

Louis Kottmann
Louis Kottmann

Reputation: 16628

You don't need that with Parallel.Foreach: it only executes the foreach in as many thread as there are processors available, but it returns synchronously.

More information can be found here

Upvotes: 20

Related Questions