Reputation: 353
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
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
Reputation: 39500
Yes - Parallel.ForEach will block. It's a synchronous method, which internally does its work in parallel.
Upvotes: 7