Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharpNotesForProfessionals.pdf
Скачиваний:
57
Добавлен:
20.05.2023
Размер:
6.12 Mб
Скачать

Chapter 68: Parallel LINQ (PLINQ)

Section 68.1: Simple example

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

Section 68.2: WithDegreeOfParallelism

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);

Section 68.3: AsOrdered

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 }

Section 68.4: AsUnordered

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();

GoalKicker.com – C# Notes for Professionals

391