Home

Search

C# Parallel.Invoke: Run Methods on Separate Threads

Use Parallel.Invoke to run methods in parallel. A static void method can be used as an Action.

dot net perls

Parallel.Invoke. A program needs to do many things, and the order they occur is not important. Instead of using complicated threading logic, we can use Parallel.Invoke.

Part of System.Threading.Tasks, Parallel.Invoke is a simple method to use. We pass Actions to it. The name of a static void method will work as an Action.

An example. This program introduces 3 test methods: Test, Test 2, and Test 3. We make sure the add "using System.Threading.Tasks" to the top of the program.
Invoke: We call Parallel.Invoke with the names of our 3 test methods. They are run in parallel.
Test: This method contains some slow logic that calls Math.Sqrt. When the 3 methods are run, Test() always finishes last.
And: This is because the expensive logic in Test() is being run concurrently with the other Test methods.
C# program that uses Parallel.Invoke using System; using System.Threading.Tasks; class Program { static void Test() { // This method always finishes last, because the methods are run in parallel. // ... And this one has some computations in it that slow it down. for (int i = 0; i < 1000000; i++) { double value = Math.Sqrt(i); if (value == -1) { return; } } Console.WriteLine("Test"); } static void Test2() { Console.WriteLine("Test2"); } static void Test3() { Console.WriteLine("Test3"); } static void Main() { Parallel.Invoke(Test, Test2, Test3); } } Output Test2 Test3 Test

Joining. When we call Parallel.Invoke, do all the threads terminate before the following statements are run? This program tests the joining behavior for these parallel threads.
And: All the threads created by Parallel.Invoke are joined before the next statement (following Parallel.Invoke) is executed.
C# program that tests Parallel.Invoke using System; using System.Threading.Tasks; class Program { static void Test() { Console.WriteLine("Test"); } static void Test2() { Console.WriteLine("Test2"); } static void Test3() { Console.WriteLine("Test3"); } static void Main() { Parallel.Invoke(Test, Test2, Test3); Console.WriteLine("[INTERMEDIATE]"); Parallel.Invoke(Test, Test2, Test3); } } Output Test Test3 Test2 [INTERMEDIATE] Test Test3 Test2

A summary. In my experience, Parallel.Invoke is the simplest way to have multithreading in a program. You can run methods on separate processor cores with little additional code.Parallel.For

Home

© 2007-2020 sam allen. send bug reports to info@dotnetperls.com.