The final concurrency feature we’re going to look at is data parallelism. This is where concurrency is driven by having lots of data items, rather than by explicitly creating numerous tasks or threads. It can be a simple approach to parallelism because you don’t have to tell the .NET Framework anything about how you want it to split up the work.
With tasks, the .NET Framework has no idea how many tasks you plan to create when you create the first one, but with data parallelism, it has the opportunity to see more of the problem before deciding how to spread the load across the available logical processors. So in some scenarios, it may be able to make more efficient use of the available resources.
Parallel class provides
a couple of methods for performing data-driven parallel execution. Its
ForEach methods are
similar in concept to C#
foreach loops, but rather than
iterating through collections one item at a time, on a system with
multiple logical processors available it will process multiple items
Example 16-24 uses
Parallel.For. This code calculates pixel values for a fractal known as the Mandelbrot set, a popular parallelism demonstration because each pixel value can be calculated entirely independently of all the others, so the scope for parallel execution is effectively endless (unless machines with more logical processors than pixels become available). And since it’s a relatively expensive computation, ...