Parallel ForEach Loops

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 ParallelLoopOptions, the ParallelLoopState with Break and 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 ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.