9

Can somebody explain me one thing. As I understand AsParallel() executes in own task. So, if query return huge amount of data the variable 'd' can be empty at time when 'foreach' started to execute Console.WriteLine?

var integerList = Enumerable.Range(1, 100);
var d = from x in integerList.AsParallel()
where x <= 25
select x;
foreach (var v in d)
{
Console.WriteLine(v);
}
Rakshit Pai
  • 291
  • 2
  • 15
user628147
  • 361
  • 1
  • 5
  • 7

2 Answers2

3

AsParallel is a PLINQ feature. PLINQ automatically parallelizes local LINQ queries. PLINQ has the advantage of being easy to use in that it offloads the burden of both work partitioning and result collation to the Framework.

To use PLINQ, simply call AsParallel() on the input sequence and then continue the LINQ query as usual.

Variable d in your case can not be empty only because PLINQ. If it will be empty that means there is no elements in the collection that satisfy the condition x <= 25.

You can read more here

oxilumin
  • 4,775
  • 2
  • 18
  • 25
1

No. Once you have added .AsParallel(), PLINQ will transparently execute the Where, OrderBy, and Select on all of the available processors using classic data parallel evaluation techniques. Actually query isn't executed at all until you 'touch' it in foreach loop (PLINQ uses deffered execution just as LINQ). Main thread will halt execution until return from query execution as usual.

Additional info here..

Petr Abdulin
  • 33,883
  • 9
  • 62
  • 96