Introducing Parallel Classes

Parallelism in the .NET Framework 4.0 is possible due to a number of classes, some responsible for maintaining the architecture of the TPL and some for performing operations in a concurrent fashion. The following subsection provides a brief coverage of the most important classes, describing their purpose.

The Parallel Class

The System.Threading.Tasks.Parallel class is one of the most important classes in parallel computing, because it provides shared methods for running concurrent tasks and for executing parallel loops. In this chapter you can find several examples of usage of this class; for now you just need to know that it provides the Invoke, For, and ForEach shared methods. The first one enables running multiple tasks concurrently, whereas the other ones enable executing loops in parallel.

The TaskScheduler Class

The System.Threading.Tasks.TaskScheduler class is responsible for the low-level work of sending tasks to the thread queue. This means that when you start a new concurrent task, the task is sent to the scheduler that checks for thread availability in the .NET thread pool. If a thread is available, the task is pushed into the thread and executed. Generally you do not interact with the task scheduler. (The class exposes some members that you can use to understand the tasks state.) The first property is Current, which retrieves the instance of the running task scheduler. This is required to access information. For example, you can understand the concurrency level by reading the MaximumConcurrencyLevel property as follows:

image

There are also some protected methods that can be used to force tasks’ execution (such as QueueTask and TryDequeue) but these are accessible if you want to create your custom task scheduler, which is beyond of the scope in this chapter.

The TaskFactory Class

The System.Threading.Tasks.TaskFactory class provides support for generating and running new tasks and is generally exposed as a shared property of the Task class, as explained in the next section about tasks. The most important member is the StartNew method, which enables creating a new task and automatically starting it.

The ParallelOptions Class

The System.Threading.Tasks.ParallelOptions class provides a way for setting options on tasks’ creation. Specifically it provides properties for setting tasks’ cancellation properties (CancellationToken), the instance of the scheduler (TaskScheduler), and the maximum number of threads that a task is split across (MaxDegreeOfParallelism).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.84.150