TPL: does a ForEach wait until all tasks are complete?

sfun28 used Ask the Experts™

If I use Parallel.ForEach, do I have to keep checking the ParallelLoopResult's IsComplete property, or does ForEach block until all items in the Enumeration are processed?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Distinguished Expert 2017
Hi sfun28;

The documentation for the Parallel.ForEach states that the, "ForEach loop works like a For loop", and each of them run in a different thread and therefore non-blocking. As for the ParallelLoopResult it is a data structure which is filled in by the system and so if you want to see if the Parallel process is completed you need to check the value of IsComplete, documentation can be found at:

From Microsoft Documentation at

A ForEach() loop works like a For loop: The source collection is partitioned and the work is scheduled on multiple threads based on the system environment. The more processors on the system, the faster the parallel method runs. For some source collections, a sequential loop may be faster, depending on the size of the source, and the kind of work being performed.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial