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.
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.
Parallel.Invoke
with the names of our 3 test methods. They are run in parallel.Math.Sqrt
. When the 3 methods are run, Test()
always finishes last.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
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.
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
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.