C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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