CSharp - Parallel LINQ WithExecutionMode

Introduction

The WithExecutionMode operator overrides the analysis that PLINQ performs and force parallel execution.

Prototypes

public static ParallelQuery<T> WithExecutionMode<T>(
    this ParallelQuery<T> source,
    ParallelExecutionMode executionMode
)

ParallelExecutionMode has two values:

ValueMeaning
Default let PLINQ decide
ForceParallelismperform parallel execution regardless

The following code shows the use of the WithExecutionMode operator to force parallel execution.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

class Program//from  w  w w .j  a  v  a  2 s. c om
{
    static void Main(string[] args)
    {
        string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        
        IEnumerable<string> results = codeNames
            .AsParallel()
            .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
            .Where(p => p.Contains('o'))
            .Select(p => p);
        
        foreach (string president in results) {
            Console.WriteLine("Match: {0}", president);
        }

    }
}

Result