In .NET's PLINQ, what does AsParallel() change about the order of query results, and when is a PLINQ query slower than plain LINQ?
answer
- unordered unless you ask
- AsOrdered and order-imposing operators
- partition, run, merge overhead
- ForAll skips the merge
basics
~20 sAsParallel() drops the guarantee that results come back in source order; AsOrdered() or OrderBy restores it at a cost. PLINQ is slower than plain LINQ when each element's work is too cheap to pay for partitioning, coordinating threads and merging results.
solid answer
~40 sAfter `AsParallel()`, PLINQ partitions the source, runs the operators on several threads (by default `Environment.ProcessorCount`, capped at 512) and merges the results, and by default it does **not** preserve source order. `AsOrdered()` restores order for the rest of the query, and `OrderBy`/`ThenBy` impose their own; both add bookkeeping at merge time. An array source can come back in order by accident, so only `AsOrdered` is a guarantee. PLINQ loses to plain LINQ when the per-element delegate is cheap, when the source is small, when delegates contend on a shared lock, and for some query shapes it falls back to sequential execution, so you pay the setup for nothing. `ForAll` avoids the merge back to one thread when you only need a side effect per element.
code
csharp · 21 lines// A lazily produced source, like File.ReadLines: not an array or IList<T>
IEnumerable<int> records = Enumerable.Range(1, 200_000).Select(n => n);
int[] expected = records.Where(n => n % 3 == 0).Select(n => n * 2).ToArray();
int[] unordered = records.AsParallel()
.Where(n => n % 3 == 0).Select(n => n * 2).ToArray();
int[] ordered = records.AsParallel().AsOrdered()
.Where(n => n % 3 == 0).Select(n => n * 2).ToArray();
Console.WriteLine($"same elements: {unordered.Order().SequenceEqual(expected)}"); // True
Console.WriteLine($"unordered in order: {unordered.SequenceEqual(expected)}"); // False on these runs; never guaranteed
Console.WriteLine($"AsOrdered in order: {ordered.SequenceEqual(expected)}"); // True, guaranteed
int hits = 0;
records.AsParallel().WithDegreeOfParallelism(4)
.Where(n => n % 1000 == 0)
.ForAll(n => Interlocked.Increment(ref hits)); // runs on the workers, no merge step
Console.WriteLine($"ForAll handled {hits} items"); // 200
try { records.AsParallel().WithDegreeOfParallelism(513).Count(); }
catch (ArgumentOutOfRangeException) { Console.WriteLine("WithDegreeOfParallelism(513) throws ArgumentOutOfRangeException"); }go deeper
Recall that AsParallel() runs a LINQ query on several threads and that results may come back in a different order than the source.
Explain partition, run and merge, the default degree of parallelism, what AsOrdered and OrderBy guarantee, and why ForAll is cheaper than foreach.
Diagnose a PLINQ query that got slower or shuffled output: cheap delegates, shared locks, sequential fallback shapes, and order that only held by accident on arrays.
Treat PLINQ as an optimisation that must earn its place with a measurement on representative data, and keep parallel queries away from shared mutable state by design.
## What `AsParallel()` turns on **PLINQ** (Parallel LINQ) is the set of `ParallelEnumerable` operators you reach by calling `AsParallel()` on an `IEnumerable<T>`. The result is a `ParallelQuery<T>`, and every operator after it (`Where`, `Select`, `Sum`, `ToList`...) binds to the parallel implementation. Running a query then has three phases: 1. **Partition** the source into chunks that workers can take. 2. **Run** the operators on each partition, on several thread pool threads at once. The default degree of parallelism is `Math.Min(Environment.ProcessorCount, 512)` in the runtime source; `WithDegreeOfParallelism(n)` accepts 1 to 512 and throws `ArgumentOutOfRangeException` outside that range. 3. **Merge** the per-thread results back into one sequence for `foreach`, `ToList` or `ToArray`. Take the nightly image job: computing a perceptual hash for a batch of thumbnails already decoded into memory with `thumbnails.AsParallel().Select(ComputeHash).ToList()` can keep every core busy, because each delegate call is expensive compared with the overhead. ## Order is not guaranteed unless you ask for it The PLINQ docs are explicit: by default PLINQ does not preserve the order of the source sequence, unlike LINQ to Objects. Elements reach the merge as each thread finishes them. - **`AsOrdered()`** right after `AsParallel()` makes the query keep source order. It costs extra bookkeeping across partitions and at merge time. - **`AsUnordered()`** turns the requirement off again for later operators that do not need it. - **`OrderBy` and `ThenBy`** are treated as if followed by `AsOrdered()`, so their order holds for the rest of the query. - **`ForAll`** runs non-deterministically in parallel whether or not the query is ordered. A trap worth knowing: in a test run with an **array** source, an unordered `Where`/`Select`/`ToArray` came back in source order every time, while the same query over a lazily enumerated source (the shape of `File.ReadLines`) came back shuffled on every run, and iterating the array query with `foreach` lost order too. Order that appears in a test is an implementation detail; only `AsOrdered` is a promise. ## Where the time goes | Cost | Why PLINQ pays it | |---|---| | Partitioning | the source must be split and handed out, under synchronisation for non-indexable sources | | Thread coordination | work items are queued to the pool and workers are joined at the end | | Merging | `ToList`, `ToArray` and `foreach` serialise results onto one thread | | Ordering | `AsOrdered` keeps indices and buffers results to emit them in sequence | The first factor the docs name is the total work: the cost per element multiplied by the number of elements has to outweigh these costs. Ordering, merging and shared state are the others. ## When PLINQ is slower than plain LINQ 1. **Cheap delegates.** Squaring numbers or comparing short strings costs nanoseconds per element; the overhead above dominates. 2. **Small sources.** A few dozen elements cannot amortise starting several workers. 3. **Shared mutable state.** A delegate that takes a lock or updates one shared object serialises the workers, and the cache lines bounce between cores. 4. **Blocking delegates.** A delegate that waits on I/O ties up pool threads; PLINQ is for CPU work, not for overlapping waits. 5. **Shapes that fall back to sequential.** The docs list query shapes PLINQ runs sequentially by default because parallelising them is usually slower: positional operators such as an indexed `Select` or `ElementAt` after a filter or reordering, `Take`/`Skip` on rearranged indices, and `Zip`, `SequenceEqual`, `Concat` and `Reverse` on non-indexable sources. `WithExecutionMode(ParallelExecutionMode.ForceParallelism)` overrides that, which is only worth it when measurements say so. ## Merging, `ForAll` and errors - `WithMergeOptions(ParallelMergeOptions...)` trades latency for throughput: `NotBuffered` yields elements as soon as they are ready, `FullyBuffered` waits for all of them. - `ForAll(action)` runs the action on the worker threads themselves with no merge step, the cheapest way to finish a query whose results are side effects. The action must then be thread-safe. - An exception in any delegate surfaces as an `AggregateException` from the operator that ran the query. Whether a particular PLINQ query beats its sequential twin is a measurement question, and the answer depends on the machine; the mechanism above tells you where to expect a win and where to expect a loss.
- Why can a PLINQ query over an array keep source order in tests and lose it on a streamed source in production?Order without `AsOrdered` is never promised. With an indexable source PLINQ can split the work into contiguous ranges, and `ToArray` may join them back in range order, so a test happens to pass; a lazily enumerated source is handed out in chunks as workers ask, and results interleave. Add `AsOrdered()` wherever the order matters.
- What does ParallelExecutionMode.ForceParallelism change in a PLINQ query?By default PLINQ inspects the query's shape and runs certain shapes sequentially, such as positional operators after a filter or `Zip` and `Concat` over non-indexable sources, because the parallel algorithms for them carry high overhead. `WithExecutionMode(ParallelExecutionMode.ForceParallelism)` makes it parallelise the whole query anyway; use it only when a measurement shows a gain.
- AsParallel() keeps results in source order, just like LINQ to Objects
- PLINQ always speeds up a query on a multi-core machine
- WithDegreeOfParallelism accepts any thread count you choose
- ForAll merges results back onto the calling thread, like foreach
- An ordered result in a test over an array proves the query preserves order