Parallel Programming in C# Using the Parallel Class

Overview of Parallel Class Methods

The Parallel class provides three primary methods for structured parallel execution:

  • Parallel.Invoke: Executes multiple delegates concurrently
  • Parallel.For: Parallel equivalent of standard for loops
  • Parallel.ForEach: Parallel equivalent of foreach loops

These methods block the calling thread until all operation complete. Similar to PLINQ, unhandled exceptions terminate worker threads after completing current iterations and wrap exceptions in AggregateException.

Important Considerations

  1. Optimized for compute-bound operations, not I/O-bound tasks
  2. Iterations execute in unordered sequence
  3. Require thread synchronization for shared variables
  4. Synchronous execution may be faster for trivial operations
  5. Database operations require proper transaction handling
  6. ForEach general outperforms For for large collections

Parallel.Invoke Method

Executes multiple Action delegates concurrently and waits for completion:

public static void Invoke(params Action[] actions);

For fewer than 10 tasks, prefer explicit Task creation for better performance.

Implementation Examples

// Basic invocation pattern
void ExecuteParallelActions()
{
    Parallel.Invoke(PerformTaskOne, PerformTaskTwo);
}

void PerformTaskOne() => Console.WriteLine("Task One");
void PerformTaskTwo() => Console.WriteLine("Task Two");

// Dynamic action generation
void ExecuteMultipleActions()
{
    Action task = () => Console.WriteLine($"Thread ID: {Thread.CurrentThread.ManagedThreadId}");
    Parallel.Invoke(Enumerable.Repeat(task, 12).ToArray());
}

Parallel.For Implementation

Provides parallel iteration similar to standard for loops:

// Sequential iteration
for (int i = 0; i < 100; i++) 
    ProcessItem(i);

// Parallel equivalent
Parallel.For(0, 100, i => ProcessItem(i));

Configuration Options

ParallelOptions provides configuration capabilities:

var options = new ParallelOptions
{
    CancellationToken = cancellationSource.Token,
    MaxDegreeOfParallelism = Environment.ProcessorCount - 1,
    TaskScheduler = TaskScheduler.Default
};

Execution Control

void RunParallelFor(int iterations)
{
    var results = new ConcurrentBag<Item>();
    ParallelLoopResult status = Parallel.For(0, iterations, i =>
    {
        results.Add(new Item { Index = i, Name = "Item_" + i });
        Thread.Sleep(20);
    });
}

Loop Termination

void TerminateEarly()
{
    ParallelLoopResult result = Parallel.For(0, 50, (int i, ParallelLoopState state) =>
    {
        if (i > 25) state.Break();
        Console.WriteLine($"Index: {i}");
    });
}

Cancellation Handling

void HandleCancellation()
{
    var cancelSource = new CancellationTokenSource(500);
    try
    {
        Parallel.For(0, 100, new ParallelOptions { 
            CancellationToken = cancelSource.Token 
        }, index =>
        {
            // Processing logic
        });
    }
    catch (OperationCanceledException)
    {
        Console.WriteLine("Operation canceled");
    }
}

Parallel.ForEach Implementation

Processes enumerable colections in parallel:

// Basic unordered execution
void ProcessCollection()
{
    string[] elements = { "alpha", "beta", "gamma", "delta" };
    Parallel.ForEach(elements, item =>
    {
        Console.WriteLine(item);
    });
}

// With index tracking
void ProcessWithIndex()
{
    string[] dataSet = { "first", "second", "third", "fourth" };
    Parallel.ForEach(dataSet, (item, state, position) =>
    {
        Console.WriteLine($"Element: {item} at Position: {position}");
    });
}

Tags: C# Parallel Class Parallel.Invoke Parallel.For Parallel.ForEach

Posted on Sun, 06 Sep 2026 16:08:50 +0000 by Ohio Guy