Just as the
Parallel.For method resembles a C# for loop, the
Parallel.ForEach method is designed to mirror the C#
foreach loop. Given an enumerable sequence, the
ForEach method allows for the parallel execution of a loop body for each of the elements in the given sequence.
Most of the concepts discussed in our coverage of
For carry over to the
ForEach case, as well, including the use of
Stop methods, and the
ParallelLoopResult. Similarly, thread-local state can be associated with the workers that carry out the loop’s work.
In what follows, we focus on the additional concepts introduced for the
ForEach loop that are unique to this kind of loop. But first, let’s consider ...