sst4460
sst4460

Reputation: 353

Will Parallel.Foreach block until it is done?

If I have code similar to this:

foreach (Item child in item.Children)
{
     // Do stuff
     ParallelOptions options = new ParallelOptions();
     options.MaxDegreeOfParallelism = 3;
     Parallel.ForEach(items, i => DoStuff());
}

Is the Parallel.Foreach going to finish all of its items before moving on to the next foreach item?

Upvotes: 1

Views: 1914

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239684

I've gone with a slightly bizarre way to demonstrate the desired property below, because I can't find any nice excerpts from the documentation for e.g. Parallel.ForEach that just come out and states that the loops are completed before the methods return:


Yes. Note the return type of Parallel.Foreach is a ParallelLoopResult which contains information that can only be available once all of the operations have completed, such as IsCompleted:

Gets whether the loop ran to completion, such that all iterations of the loop were executed and the loop didn't receive a request to end prematurely.

ParallelLoopResult is a struct - and so whatever value is returned from Parallel.ForEach cannot be altered after the return from that method.

Upvotes: 1

Will Dean
Will Dean

Reputation: 39500

Yes - Parallel.ForEach will block. It's a synchronous method, which internally does its work in parallel.

Upvotes: 7

Related Questions