One of the nice things about linq was that endless data sources were processed lazily on request. I tried to parallelize my queries and found that lazy loading was not working. For instance...
class Program
{
static void Main(string[] args)
{
var source = Generator();
var next = source.AsParallel().Select(i => ExpensiveCall(i));
foreach (var i in next)
{
System.Console.WriteLine(i);
}
}
public static IEnumerable<int> Generator()
{
int i = 0;
while (true)
{
yield return i;
i++;
}
}
public static int ExpensiveCall(int arg)
{
System.Threading.Thread.Sleep(5000);
return arg*arg;
}
}
This program does not give any results, apparently, because at each step it is waiting for all generator calls to dry, which, of course, never. If I pull out the AsParallel call, it works fine. So, how do I get a nice lazy load when using PLINQ to improve the performance of my applications?
source
share