Parallel Class
Learn to execute code loops and independent methods concurrently using the static Parallel class for data parallelism.
While the Task class is the core of the Task Parallel Library (TPL), creating and managing individual Task objects for simple loops or batches of operations can be cumbersome. For these scenarios, the TPL provides the Parallel class.
The Parallel class is a static helper that provides a higher-level abstraction for data parallelism. It uses thread pool threads to execute code in parallel, automatically utilizing multiple CPU cores. It offers three primary methods:
Invoke(): Executes an array of distinctActiondelegates in parallel.For(): A parallel version of the standardforloop.ForEach(): A parallel version of the standardforeachloop.
Note: Unlike Task.Run(), methods in the Parallel class are synchronous (blocking). The calling thread waits until all parallel operations are complete before proceeding.
Parallel invocation
The Parallel.Invoke() method is used when you have several independent tasks that need to run concurrently, and you need to wait for all of them to finish. It accepts an array of Action delegates or separate methods as arguments.