Home
Map
Parallel.Invoke ExampleUse Parallel.Invoke to run methods in parallel. A static void method can be used as an Action.
C#
This page was last reviewed on Oct 10, 2023.
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.
Parallel.For
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.
Detail We call Parallel.Invoke with the names of our 3 test methods. They are run in parallel.
Detail 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.
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); } }
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.
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); } }
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.