Chapter 23. Parallel Programming
In this chapter, we cover the multithreading APIs and constructs aimed at leveraging multicore processors:
-
Parallel LINQ or PLINQ
-
The
Parallel
class -
The task parallelism constructs
-
The concurrent collections
These were added in Framework 4.0 and are collectively known (loosely) as PFX (Parallel Framework). The Parallel
class together with the task parallelism constructs is called the Task Parallel Library or TPL.
You’ll need to be comfortable with the fundamentals in Chapter 14 before reading this chapter—particularly locking, thread safety, and the Task
class.
Why PFX?
Over the past 10 years, CPU manufacturers have shifted from single- to multicore processors. This is problematic for us as programmers because single-threaded code does not automatically run faster as a result of those extra cores.
Leveraging multiple cores is easy for most server applications, where each thread can independently handle a separate client request, but is harder on the desktop—because it typically requires that you take your computationally intensive code and do the following:
-
Partition it into small chunks.
-
Execute those chunks in parallel via multithreading.
-
Collate the results as they become available, in a thread-safe and performant manner.
Although you can do all of this with the classic multithreading constructs, it’s awkward—particularly the steps of partitioning and collating. A further problem is that the usual strategy of locking for thread ...
Get C# 7.0 in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.