Parallel Invoke in CSharp

Here’s a comprehensive lesson on the Parallel Invoke method in C#, covering all relevant topics with detailed code examples.


Understanding Parallel Invoke Method in C#

The Parallel Invoke method in C# allows for the simultaneous execution of multiple delegates, enabling efficient parallel processing. This lesson provides an in-depth understanding of the Parallel Invoke method, covering various topics with comprehensive code examples.

Basic Parallel Invocation

The Parallel Invoke method can execute multiple delegates concurrently. Here’s an example demonstrating its basic usage:

using System;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        Parallel.Invoke(
            () => Console.WriteLine("Task 1 started."),
            () => Console.WriteLine("Task 2 started."),
            () => Console.WriteLine("Task 3 started.")
        );
    }
}

Parallel Invocation with Parameters

Passing parameters to the delegates in Parallel Invoke is possible, enabling the execution of parameterized tasks simultaneously. Here’s an example illustrating this feature:

using System;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3 };

        Parallel.Invoke(
            () => PrintNumber(numbers[0]),
            () => PrintNumber(numbers[1]),
            () => PrintNumber(numbers[2])
        );
    }

    static void PrintNumber(int num)
    {
        Console.WriteLine("Number: " + num);
    }
}

Exception Handling in Parallel Invoke

Handling exceptions in Parallel Invoke is crucial for maintaining the stability of the application. Here’s an example demonstrating exception handling within Parallel Invoke:

using System;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        try
        {
            Parallel.Invoke(
                () => { throw new Exception("Error in Task 1."); },
                () => { throw new Exception("Error in Task 2."); },
                () => { throw new Exception("Error in Task 3."); }
            );
        }
        catch (AggregateException ex)
        {
            foreach (var innerEx in ex.InnerExceptions)
            {
                Console.WriteLine("Exception: " + innerEx.Message);
            }
        }
    }
}

By mastering the Parallel Invoke method in C#, developers can leverage parallel processing capabilities effectively, enabling efficient execution of multiple tasks concurrently. Understanding its various features, including basic invocation, parameter passing, and exception handling, is crucial for building responsive and high-performance applications.