Using the Parallel class

TPL provides a reach API to compose a parallel program. However, it is quite verbose, and if we write a simple code, there are easier way to parallelize it. For common tasks such as running some code in parallel and parallelizing the for and foreach loops, there is a Parallel class that provides a simple and easy to use API.

Parallel.Invoke

This method executes actions in parallel if the CPU has multiple cores and supports multiple threads. If the CPU has only one core, actions will be executed synchronously. This method blocks the calling thread until all the actions are completed:

Parallel.Invoke( () => Console.WriteLine("Action 1"), () => { Thread.SpinWait(10000); Console.WriteLine("Action 2"); }, () => Console.WriteLine("Action ...

Get Mastering C# Concurrency 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.