CSharp - Parallel LINQ Parallelism Degree

Introduction

You can request that PLINQ limit the number of partitions processed simultaneously using the WithDegreeofParallelism extension method.

This method takes an int argument that states the maximum number of partitions that should be processed at once.

It sets an upper limit.

PLINQ may decide to use fewer than you have specified.

Demo

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

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

Result

The code above specified a maximum degree of 2, meaning that we want at most two data partitions to be processed simultaneously.

Related Topic