Chapter68:ParallelLINQ(PLINQ)

No Comments

Section68.1:Simpleexample

ThisexampleshowshowPLINQcanbeusedtocalculatetheevennumbersbetween1and10,000usingmultiple threads. Note that the resulting list will won’t be ordered!

varsequence=Enumerable.Range(1,10000);

varevenNumbers=sequence.AsParallel()

.Where(x=>x%2==0)

.ToList();

//evenNumbers={4,26,28,30,…}

//Orderwillvarywithdifferentruns

Section68.2:WithDegreeOfParallelism

The degree of parallelism is the maximum number of concurrently executing tasks that will be used to process the query.

varsequence=Enumerable.Range(1,10000);

varevenNumbers=sequence.AsParallel()

.WithDegreeOfParallelism(4)

.Where(x=>x%2==0);

Section68.3:AsOrdered

ThisexampleshowshowPLINQcanbeusedtocalculatetheevennumbersbetween1and10,000usingmultiple threads.Orderwillbemaintainedintheresultinglist,howeverkeepinmindthatAsOrderedmayhurtperformance foralargenumbersofelements,soun-orderedprocessingispreferredwhenpossible.

varsequence=Enumerable.Range(1,10000);

varevenNumbers=sequence.AsParallel()

.AsOrdered()

.Where(x=>x%2==0)

.ToList();

//evenNumbers={2,4,6,8,…,10000}

Section68.4:AsUnordered

Ordered sequences may hurt performance when dealing with a large number of elements. To mitigate this, it’s possible to call AsUnorderedwhen the sequence order is no longer necessary.

varsequence=Enumerable.Range(1,10000).Select(x=>-1*x);//-1,-2,

varevenNumbers=sequence.AsParallel()

.OrderBy(x=>x)

.Take(5000)

.AsUnordered()

.Where(x=>x%2==0)//Thislinewon’tbeaffectedbyordering

.ToList();

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts
No Comments

Recent Posts