Deferred execution in parallel LINQ in .NET C#
August 17, 2016 1 Comment
If you are familiar with LINQ then you are probably aware of the notion of deferred execution: queries are not carried out until they are needed. This is not different in parallel LINQ either. Let’s see an example:
Set up a data source:
int[] integerArray = new int[100];
for (int i = 0; i < integerArray.Length; i++)
{
integerArray[i] = i;
}
Define a parallel query:
IEnumerable<double> results =
integerArray.AsParallel().Select(item =>
{
return Math.Sqrt(item);
});
The query has not been carried out at this point. It is carried out when the following foreach loop starts:
double sum = 0;
foreach (double result in results)
{
sum += result;
}
Console.WriteLine("Total {0}", sum);
You can force query execution with the same extension methods as in “normal” LINQ, such as ToList, ToArray etc.:
IEnumerable<double> results =
integerArray.AsParallel().Select(item =>
{
return Math.Sqrt(item);
}).ToList();
In this case the query is executed as soon as it has been defined.
View the list of posts on the Task Parallel Library here.