DEV Community

Cover image for PLINQ Extension Methods in C#
Common Khadka
Common Khadka

Posted on

PLINQ Extension Methods in C#

Parallel LINQ (PLINQ) is an extension of LINQ that enables parallel processing of queries to improve performance by utilizing multiple cores of a processor. Below is a list of PLINQ extension methods along with code snippets demonstrating their usage.


1. AsParallel

Converts an IEnumerable to a parallel query, enabling parallel execution.

var numbers = Enumerable.Range(1, 10);
var parallelQuery = numbers.AsParallel().Where(n => n % 2 == 0);
foreach (var num in parallelQuery)
{
    Console.WriteLine(num);
}
Enter fullscreen mode Exit fullscreen mode

2. WithDegreeOfParallelism

Limits the number of processor cores used for the query execution.

var numbers = Enumerable.Range(1, 20);
var parallelQuery = numbers.AsParallel()
                           .WithDegreeOfParallelism(2) // Limits to 2 cores
                           .Where(n => n % 2 == 0);
foreach (var num in parallelQuery)
{
    Console.WriteLine(num);
}
Enter fullscreen mode Exit fullscreen mode

3. ParallelEnumerable.Range

Generates a range of numbers in parallel.

var parallelRange = ParallelEnumerable.Range(1, 10);
parallelRange.ForAll(Console.WriteLine);
Enter fullscreen mode Exit fullscreen mode

4. ParallelEnumerable.Repeat

Generates a sequence where a specified value is repeated multiple times in parallel.

var repeatedValues = ParallelEnumerable.Repeat("Hello", 5);
repeatedValues.ForAll(Console.WriteLine);
Enter fullscreen mode Exit fullscreen mode

5. ParallelEnumerable.Empty

Returns an empty parallel sequence.

var emptySequence = ParallelEnumerable.Empty<int>();
Console.WriteLine("Count: " + emptySequence.Count());
Enter fullscreen mode Exit fullscreen mode

6. AsSequential

Forces a PLINQ query to process sequentially instead of in parallel.

var numbers = Enumerable.Range(1, 10).AsParallel();
var sequentialQuery = numbers.AsSequential().Where(n => n % 2 == 0);
foreach (var num in sequentialQuery)
{
    Console.WriteLine(num);
}
Enter fullscreen mode Exit fullscreen mode

7. AsOrdered

Preserves the ordering of the original sequence in a PLINQ query.

var numbers = Enumerable.Range(1, 10).AsParallel().AsOrdered();
foreach (var num in numbers)
{
    Console.WriteLine(num);
}
Enter fullscreen mode Exit fullscreen mode

8. AsUnordered

Removes ordering constraints for better parallel performance.

var numbers = Enumerable.Range(1, 10).AsParallel().AsUnordered();
numbers.ForAll(Console.WriteLine);
Enter fullscreen mode Exit fullscreen mode

9. WithCancellation

Enables cancellation of a PLINQ query using a CancellationToken.

var cts = new CancellationTokenSource();
var numbers = Enumerable.Range(1, 100).AsParallel().WithCancellation(cts.Token);
Task.Run(() => cts.Cancel());
try
{
    foreach (var num in numbers)
    {
        Console.WriteLine(num);
    }
}
catch (OperationCanceledException)
{
    Console.WriteLine("Query was canceled.");
}
Enter fullscreen mode Exit fullscreen mode

10. WithMergeOptions

Specifies how results should be merged after parallel execution.

var numbers = Enumerable.Range(1, 10).AsParallel()
                        .WithMergeOptions(ParallelMergeOptions.NotBuffered);
numbers.ForAll(Console.WriteLine);
Enter fullscreen mode Exit fullscreen mode

11. WithExecutionMode

Forces a query to run in parallel or sequential mode.

var numbers = Enumerable.Range(1, 10).AsParallel()
                        .WithExecutionMode(ParallelExecutionMode.ForceParallelism);
numbers.ForAll(Console.WriteLine);
Enter fullscreen mode Exit fullscreen mode

12. ForAll

Executes a parallel query and applies an action to each element.

var numbers = Enumerable.Range(1, 10).AsParallel();
numbers.ForAll(Console.WriteLine);
Enter fullscreen mode Exit fullscreen mode

Conclusion

PLINQ provides powerful methods to enable efficient parallel processing in C#. Understanding these methods can help improve performance in applications that handle large data processing tasks.


References


Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay