Home
C#
Parallel.Invoke Example
Updated Apr 16, 2024
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.
Parallel.For
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.
Start We call Parallel.Invoke with the names of our 3 test methods. They are run in parallel.
Info The Test 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
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 16, 2024 (edit).
Home
Changes
© 2007-2025 Sam Allen