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.
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 3")); Console.WriteLine("End");
After running the preceding lines of code, we get the following output:
Action 1 Action 3 Action 2 End
We can provide the ParallelOptions
class instance to this method to configure...