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.
var results = numbers.AsParallel().Where(IsPrime).ToList(); long total = numbers.AsParallel().Sum(n => (long)n);
Try it
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.
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
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 useAsOrdered().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()versusforeach.foreachover aParallelQuerymerges 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
asynccode andTask.WhenAll(); for loops with side effects seeParallel.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()andSkip()on unordered queries may return any matching elements; combine withAsOrdered()for first-n semantics. - Printing timings is meaningless here: results depend on cores, load and JIT. Benchmark with a proper tool.