How to use Parallel LINQ in C#

By FoxLearn 1/7/2025 2:35:23 AM   3
Parallel LINQ (PLINQ) is an extension of Language Integrated Query (LINQ) that enables declarative data parallelism by utilizing multiple cores in a system to execute queries in parallel.

It was introduced as part of the .NET Framework 4 within the Parallel Extensions Library, which includes both PLINQ and the Task Parallel Library (TPL).

PLINQ improves query performance by splitting tasks into chunks that can be processed concurrently on different threads, optimizing for compute-bound operations. While PLINQ is ideal for tasks that require heavy computation, it may not always be suitable for all types of queries compared to traditional LINQ.

Consider the following LINQ query that retrieves employees whose last names start with "S":

var data = from e in employees
           where e.LastName.StartsWith("S")
           select e;

You can easily convert this query into a PLINQ query by using the AsParallel extension method, which allows the query to be executed in parallel across multiple threads:

var data = from e in employees.AsParallel()
           where e.LastName.StartsWith("S")
           select e;

If you want to ensure that the results maintain their original order, you can use the AsOrdered method:

var data = from e in employees.AsParallel().AsOrdered()
           where e.LastName.StartsWith("S")
           select e;

Alternatively, you can preserve the order of the data by passing QueryOptions.PreserveOrdering to the AsParallel method:

var data = from e in employees.AsParallel(QueryOptions.PreserveOrdering)
           where e.LastName.StartsWith("S")
           select e;

Note that using AsParallel() on small collections may actually result in slower execution than using a standard LINQ query, as parallelism introduces overhead for small datasets. If you still want to enforce parallelism, you can use the WithExecutionMode method, though this is generally not recommended unless you are certain that parallelism will provide a benefit:

var data = from e in employees.AsParallel().WithExecutionMode(ParallelExecutionMode.ForceParallelism)
           where e.LastName.StartsWith("S")
           select e;

The ParallelExecutionMode enumeration, part of the System.Linq namespace, offers two values:

  • Default: PLINQ will decide whether to use parallelism based on performance considerations.
  • ForceParallelism: PLINQ will force parallel execution even if it could result in a performance penalty.

By specifying ForceParallelism, you ensure parallel execution, but it might not always lead to performance improvements, especially for smaller datasets.