CSharp - Parallel LINQ Controlling Parallelism

Forcing Parallel Execution

You can control Parallel Execution by using the WithExecutionMode extension method, which is applied to the ParallelQuery type.

The WithExecutionMode method takes a value from the ParallelExecutionMode enumeration.

There are two such values:

default let PLINQ decide what to do
ForceParallelism use PLINQ regardless.

Demo

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

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

Result

Related Topics