PLINQ IN .Net
PLINQ Methods Example
PLINQ takes your data query and, like a team of clones, processes different parts of the data at the same time. It’s like having multiple shoppers in the store, each with a copy of the shopping list, working in parallel to finish the shopping faster.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
class PLINQMethodsExample
{
static void Main(string[] args)
{
// Example data source
var numbers = Enumerable.Range(1, 100);
// AsParallel to enable parallelization
var parallelQuery = numbers.AsParallel();
// WithDegreeOfParallelism to limit the number of processors to use
var limitedParallelismQuery = numbers.AsParallel().WithDegreeOfParallelism(2);
// WithExecutionMode to hint PLINQ on how to execute the query
var forcedParallelismQuery = numbers.AsParallel().WithExecutionMode(ParallelExecutionMode.ForceParallelism);
// AsOrdered to preserve the order of the source sequence
var orderedQuery = numbers.AsParallel().AsOrdered();
// AsSequential to buffer output and preserve order for subsequent query operators
var sequentialQuery = orderedQuery.AsSequential();
// WithCancellation to enable query cancellation
CancellationTokenSource cts = new CancellationTokenSource();
var cancellableQuery = numbers.AsParallel().WithCancellation(cts.Token);
// WithMergeOptions to control the output buffer
var fullyBufferedQuery = numbers.AsParallel().WithMergeOptions(ParallelMergeOptions.FullyBuffered);
// ForAll for immediate execution
parallelQuery.ForAll(e => DoSomething(e));
// Aggregate for custom aggregation
var sum = parallelQuery.Aggregate(
0, // Initial seed value
(subtotal, item) => subtotal + item, // An accumulator function
(total1, total2) => total1 + total2, // A function to combine the accumulated results
finalResult => finalResult); // A function to perform final transformations
// Print the sum
Console.WriteLine($"Sum: {sum}");
// Handle cancellation
Task.Run(() =>
{
Thread.Sleep(100);
cts.Cancel();
});
try
{
foreach (var n in cancellableQuery)
{
Console.WriteLine(n);
}
}
catch (OperationCanceledException)
{
Console.WriteLine("Query was canceled.");
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
static void DoSomething(int number)
{
// Simulate some work
Thread.Sleep(10);
}
}
PLINQ Methods Explanation:
- AsParallel: Used to convert numbers into a parallel query.
- WithDegreeOfParallelism: Limits the number of concurrent tasks.
- WithExecutionMode: Provides hints to PLINQ on how to execute the query.
- AsOrdered and AsSequential: Used to preserve the order of the source sequence.
- WithCancellation: Enables query cancellation with a CancellationToken.
- WithMergeOptions: Controls how results are buffered before being used in the next stage.
- ForAll: Used for immediate execution of the query.
- Aggregate: Used for custom aggregation of results.
Comments