Free mag vol1 | Page 787

CHAPTER 19  MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING Figure 19-3. Members of the System.Threading.Tasks namespace The Role of the Parallel Class A key class of the TPL is System.Threading.Tasks.Parallel. This class supports a number of methods that allow you to iterate over a collection of data (specifically, an object implementing IEnumerable) in a parallel fashion. If you were to look up the Parallel class in the .NET Framework 4.5 SDK documentation, you would see that this class supports two primary static methods, Parallel.For() and Parallel.ForEach(), each of which defines numerous overloaded versions. These methods allow you to author a body of code statements that will be processed in a parallel manner. In concept, these statements are the same sort of logic you would write in a normal looping construct (via the for or foreach C# keywords). The benefit is that the Parallel class will pluck threads from the thread pool (and manage concurrency) on your behalf. Both of these methods require you to specify an IEnumerable- or IEnumerable-compatible container that holds the data you need to process in a parallel manner. The container could be a simple array, a nongeneric collection (such as ArrayList), a generic collection (such as List), or the results of a LINQ query. In addition, you will need to make use of the System.Func and System.Action delegates to specify the target method that will be called to process the data. You’ve already encountered the Func delegate in Chapter 12, during your investigation of LINQ to Objects. Recall that Func represents a method that can have a given return value and a varied number of arguments. The Action delegate is very similar to Func, in that it allows you to point to a method taking some number of parameters. However, Action specifies a method that can only return void. 732