Parallel Class

Learn to invoke methods and iterate loops in parallel.

Overview

The core of the TPL is the Task class, but developers interested in parallelizing some jobs in their apps must also consider the Parallel class (also part of the TPL).

The Parallel class is static and allows us to execute code in parallel. Similar to a method running as part of a Task instance, the Parallel class uses pool threads to achieve parallelism and asynchronous execution. The Parallel class gives us several options:

  • Invoke(): This method accepts an array of Action delegates, either in the form of an array or as separate parameters. Methods passed in execute in parallel.
  • For(): This method resembles the for loop but iterations execute in parallel.
  • ForEach(): This method is similar to a foreach loop but executes in parallel.

Parallel invocation

The Parallel.Invoke() method accepts an array of Action delegates or an array of methods that conform to the Action delegate. The methods that are passed to Invoke(), by default, run in pool threads:

Get hands-on with 1400+ tech skills courses.