Parallel Invoke Method in C#

Parallel Invoke Method in C# with Examples

In this article, I am going to discuss the Parallel Invoke Method in C# with some examples. The Parallel Invoke Method in C# is one of the most frequently used static method of the Parallel class. This Parallel Invoke method is used to launch multiple tasks that are going to be executed in parallel. Please read the following articles before proceeding to this article.

Overview of Task Parallel Library

Parallel For Method in C#

Parallel ForEach Method in C#

Let us understand Parallel Invoke Method in C# with an example.

The following example demonstrates how to use Parallel Invoke method in C# with other methods, anonymous methods (delegates), and lambda expressions.

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ParallelProgrammingDemo
{
    public class Program
    {
        static void Main()
        {
            Parallel.Invoke(
                 NormalAction, // Invoking Normal Method
                 delegate ()   // Invoking an inline delegate 
                 {
                     Console.WriteLine($"Method 2, Thread={Thread.CurrentThread.ManagedThreadId}");
                 },
                () =>   // Invoking a lambda expression
                {
                    Console.WriteLine($"Method 3, Thread={Thread.CurrentThread.ManagedThreadId}");
                }
            );
            Console.WriteLine("Press any key to exist.");
            Console.ReadKey();
        }
        static void NormalAction()
        {
            Console.WriteLine($"Method 1, Thread={Thread.CurrentThread.ManagedThreadId}");
        }
    }
}

First run OUTPUT:

Parallel Invoke Method in C#

2nd Run OUTPUT:

Parallel Invoke Method in C#

The Parallel Invoke method is used to execute a set of operations (actions) in parallel. As you can see in the above output three threads are created to execute three actions which prove that this parallel Invoke Method executes the actions in parallel.

Note: The Parallel Invoke method in C# does not give you any guarantees about the order in which the actions are executed. Each time you execute the code, you may get a different order of output. Another important point that you need to remember is, this method is going to return when all the actions invoked by this method complete their execution. 

ParallelOptions class

As we already discussed, using the ParallelOptions class instance, we can limit the number of concurrently executing loop methods. The same thing can also be done with the Invoke method. So, using the Degree of parallelism we can specify the maximum number of threads to be used to execute the program.

Let’s understand this with an example.

In the following example, we are creating seven actions without specifying a limit to the number of parallel tasks. So, in this example, it may be possible that all seven actions can be executed concurrently.

As you can see in the below example, we are calling the DoSomeTask method seven times using the Parallel Invoke method. As part of the DoSomeTask method, we are just printing two messages with a 5000 milliseconds pause between them. The messages showing when the task started and ended and by which thread so that you will understand the order of execution.

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ParallelProgrammingDemo
{
    public class ParallelInvoke
    {
        static void Main()
        {
            Parallel.Invoke(
                    () => DoSomeTask(1),
                    () => DoSomeTask(2),
                    () => DoSomeTask(3),
                    () => DoSomeTask(4),
                    () => DoSomeTask(5),
                    () => DoSomeTask(6),
                    () => DoSomeTask(7)
                );
            Console.ReadKey();
        }
        static void DoSomeTask(int number)
        {
            Console.WriteLine($"DoSomeTask {number} started by Thread {Thread.CurrentThread.ManagedThreadId}");
            //Sleep for 5000 milliseconds
            Thread.Sleep(5000);
            Console.WriteLine($"DoSomeTask {number} completed by Thread {Thread.CurrentThread.ManagedThreadId}");
        }
    }
}

Now run the application and see the output as shown below. The output may vary in your machine.

Parallel Invoke Method in C#

You can see in the above output that each of the seven tasks started before any other completed which proofs that all the seven tasks run concurrently. In order to limit the parallelism i.e. to limit the number of threads to execute concurrently, we need to use the ParallelOptions class. We need to pass the object of ParallelOptions to the first parameter of the Invoke method.

In the below example the code is limited to three concurrent tasks.
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ParallelProgrammingDemo
{
    public class ParallelInvoke
    {
        static void Main()
        {
            //Allowing three task to execute at a time
            ParallelOptions parallelOptions = new ParallelOptions
            {
                MaxDegreeOfParallelism = 3
            };
            //parallelOptions.MaxDegreeOfParallelism = System.Environment.ProcessorCount - 1;

            //Passing ParallelOptions as the first parameter
            Parallel.Invoke(
                    parallelOptions,
                    () => DoSomeTask(1),
                    () => DoSomeTask(2),
                    () => DoSomeTask(3),
                    () => DoSomeTask(4),
                    () => DoSomeTask(5),
                    () => DoSomeTask(6),
                    () => DoSomeTask(7)
                );
            Console.ReadKey();
        }
        static void DoSomeTask(int number)
        {
            Console.WriteLine($"DoSomeTask {number} started by Thread {Thread.CurrentThread.ManagedThreadId}");
            //Sleep for 500 milliseconds
            Thread.Sleep(5000);
            Console.WriteLine($"DoSomeTask {number} completed by Thread {Thread.CurrentThread.ManagedThreadId}");
        }
    }
}

OUTPUT:

Parallel Invoke Method using ParallelOptions object in C#

As you can see from the above output that, first three tasks have started concurrently as we set the degree of parallelism to 3. When one of the tasks completes its execution then another task started. This process will continue until all of the actions have completed their work. But the most important point that you need to remember is at any given point of time, no more than three tasks are running.

In this article, I try to explain the Parallel Invoke Method in C# with some examples. I hope you understood the need and use of Parallel Invoke method in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *