Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท LINQ

PLINQ (Parallel LINQ)

Reference for PLINQ in C#: AsParallel(), AsOrdered(), ForAll(), WithDegreeOfParallelism(), exceptions and when parallel queries are actually faster.

PLINQ runs a LINQ query on several threads. You opt in by calling AsParallel() on a sequence; from then on the standard operators (Where(), Select(), Sum(), GroupBy() ...) are the parallel versions from ParallelEnumerable. The runtime partitions the source, processes the partitions on thread-pool threads and merges the results.

Parallelism pays off for CPU-bound work on large inputs where each element costs real time. For small inputs, cheap lambdas or I/O-bound work it is usually slower than a sequential query, and it makes output order unspecified unless you ask for it.

C#
var results = numbers.AsParallel().Where(IsPrime).ToList();
long total = numbers.AsParallel().Sum(n => (long)n);

Try it

C# Parallel results and ordering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# ForAll, exceptions and thread safety

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public static ParallelQuery<TSource> AsParallel<TSource>(this IEnumerable<TSource> source);

public static ParallelQuery<TSource> AsOrdered<TSource>(this ParallelQuery<TSource> source);
public static ParallelQuery<TSource> AsUnordered<TSource>(this ParallelQuery<TSource> source);
public static IEnumerable<TSource> AsSequential<TSource>(this ParallelQuery<TSource> source);

public static ParallelQuery<TSource> WithDegreeOfParallelism<TSource>(this ParallelQuery<TSource> source, int degreeOfParallelism);
public static ParallelQuery<TSource> WithCancellation<TSource>(this ParallelQuery<TSource> source, CancellationToken cancellationToken);
public static ParallelQuery<TSource> WithExecutionMode<TSource>(this ParallelQuery<TSource> source, ParallelExecutionMode executionMode);
public static ParallelQuery<TSource> WithMergeOptions<TSource>(this ParallelQuery<TSource> source, ParallelMergeOptions mergeOptions);

public static void ForAll<TSource>(this ParallelQuery<TSource> source, Action<TSource> action);
Name Description
AsParallel() Switches the rest of the query to PLINQ.
AsOrdered() Preserves source order in the results (slower). AsUnordered() drops it again.
AsSequential() Continues with the ordinary sequential operators.
WithDegreeOfParallelism(n) Upper limit of concurrently running tasks (1 to 512).
WithCancellation(token) Stops the query when the token is cancelled; throws OperationCanceledException.
WithExecutionMode(...) ForceParallelism overrides PLINQ's choice to run a query sequentially.
WithMergeOptions(...) Controls buffering between workers and the consumer.
ForAll(action) Runs action for each result on the worker threads.

Returns: a ParallelQuery<T> that executes when enumerated; aggregates return values.

Errors: exceptions thrown on workers are collected into one AggregateException.

Usage notes

  • Order is unspecified unless you call AsOrdered(). Never print an unordered parallel result directly if you need repeatable output; sort it or use AsOrdered(). OrderBy() also fixes the order for later operators.
  • Lambdas must be thread-safe. Do not mutate shared variables or non-concurrent collections inside the query. Prefer aggregation operators, thread-safe collections or Interlocked.
  • Measure before using it. Partitioning, thread scheduling and merging have a cost. A cheap lambda over a small array is almost always faster sequentially. PLINQ may decide to run some queries sequentially on its own.
  • ForAll() versus foreach. foreach over a ParallelQuery merges results back to the calling thread one at a time; ForAll() avoids that, but the action then runs concurrently.
  • Not for I/O. PLINQ blocks threads. For network or file work use async code and Task.WhenAll(); for loops with side effects see Parallel.ForEach().
  • Side effects and exceptions can leave work half-done: after an exception other workers may already have run on some elements.
  • Not every operator parallelizes well. Take(), First() and Skip() on unordered queries may return any matching elements; combine with AsOrdered() for first-n semantics.
  • Printing timings is meaningless here: results depend on cores, load and JIT. Benchmark with a proper tool.