linq
  1. linq-parallel-linqoperations

Parallel LINQ Operations (PLINQ)

Parallel LINQ (PLINQ) is an extension of LINQ that supports parallel execution of queries on multi-core processors. PLINQ automatically partitions a query and executes it in parallel across multiple processors, improving the query's performance and scalability. In this tutorial, we'll look at how to use PLINQ to execute queries in parallel.

Syntax

var query = from item in collection.AsParallel()
            where condition
            select item;

In the above syntax, AsParallel() method is used to convert a LINQ query to a PLINQ query. This method partitions the query and executes it in parallel across multiple processors.

Example

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNumbers = from n in numbers.AsParallel()
                  where n % 2 == 0
                  select n;

foreach (var number in evenNumbers)
{
    Console.WriteLine(number);
}

In the above example, we're using PLINQ to filter even numbers from an array of integers. We're using the AsParallel() method to convert the LINQ query to a PLINQ query and then applying the where clause to filter even numbers. Finally, we're iterating over the results using a foreach loop and printing them to the console.

Output

The above code will output the following:

2
4
6
8
10

Explanation

In the above syntax, we're using PLINQ to execute a query in parallel. PLINQ partitions the query and executes it in parallel across multiple processors, improving the query's performance. Here, we're using the AsParallel() method to convert a LINQ query to a PLINQ query and then applying the where clause to filter even numbers. Finally, we're iterating over the results using a foreach loop and printing them to the console.

Use

PLINQ is used when we want to execute queries in parallel and improve their performance and scalability. PLINQ is helpful when working with large data sets or queries that are computationally expensive. PLINQ automatically partitions the query and executes it in parallel across multiple processors, improving the query's performance.

Important Points

  • PLINQ queries are automatically partitioned and executed in parallel across multiple processors.
  • PLINQ queries are helpful when working with large data sets or computationally expensive queries.
  • PLINQ has some additional features like query cancellation, exception handling, and forced sequential execution.

Summary

In this tutorial, we learned about PLINQ and how to use it to execute queries in parallel. We've seen examples of using PLINQ to filter even numbers from an array of integers. PLINQ automatically partitions the query and executes it in parallel across multiple processors, improving the query's performance. We've also seen some important points to keep in mind while using PLINQ.

Published on: