This example shows how PLINQ can be used to calculate the even numbers between 1 and 10,000 using multiple threads. Note that the resulting list will won't be ordered!
var sequence = Enumerable.Range(1, 10000);
var evenNumbers = sequence.AsParallel()
.Where(x => x % 2 == 0)
.ToList();
// evenNumbers = { 4, 26, 28, 30, ... }
// Order will vary with different runs
The degree of parallelism is the maximum number of concurrently executing tasks that will be used to process the query.
var sequence = Enumerable.Range(1, 10000);
var evenNumbers = sequence.AsParallel()
.WithDegreeOfParallelism(4)
.Where(x => x % 2 == 0);
This example shows how PLINQ can be used to calculate the even numbers between 1 and 10,000 using multiple threads. Order will be maintained in the resulting list, however keep in mind that AsOrdered
may hurt performance for a large numbers of elements, so un-ordered processing is preferred when possible.
var sequence = Enumerable.Range(1, 10000);
var evenNumbers = sequence.AsParallel()
.AsOrdered()
.Where(x => x % 2 == 0)
.ToList();
// evenNumbers = { 2, 4, 6, 8, ..., 10000 }
Ordered sequences may hurt performance when dealing with a large number of elements. To mitigate this, it's possible to call AsUnordered
when the sequence order is no longer necessary.
var sequence = Enumerable.Range(1, 10000).Select(x => -1 * x); // -1, -2, ...
var evenNumbers = sequence.AsParallel()
.OrderBy(x => x)
.Take(5000)
.AsUnordered()
.Where(x => x % 2 == 0) // This line won't be affected by ordering
.ToList();