Chapter 4. Parallel Basics
This chapter covers patterns for parallel programming. Parallel programming is used to split up CPU-bound pieces of work and divide them among multiple threads. These parallel processing recipes only consider CPU-bound work. If you have naturally asynchronous operations (such as I/O-bound work) that you want to execute in parallel, then see Chapter 2, and Recipe 2.4 in particular.
The parallel processing abstractions covered in this chapter are part of the Task Parallel Library (TPL). The TPL is built into the .NET framework.
4.1 Parallel Processing of Data
Problem
You have a collection of data, and you need to perform the same operation on each element of the data. This operation is CPU-bound and may take some time.
Solution
The Parallel type contains a ForEach method specifically designed for this problem. The following example takes a collection of matrices and rotates them all:
voidRotateMatrices(IEnumerable<Matrix>matrices,floatdegrees){Parallel.ForEach(matrices,matrix=>matrix.Rotate(degrees));}
There are some situations where you’ll want to stop the loop early, such as if you encounter an invalid value. The following example inverts each matrix, but if an invalid matrix is encountered, it’ll abort the loop:
voidInvertMatrices(IEnumerable<Matrix>matrices){Parallel.ForEach(matrices,(matrix,state)=>{if(!matrix.IsInvertible)state.Stop();elsematrix.Invert();});}
This code uses ParallelLoopState.Stop to stop the loop, preventing ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access