Information Technology Reference
In-Depth Information
Here's a simple query using method call syntax that calculates n! for the
first 150 numbers:
var nums = data.Where(m => m < 150 ).
Select(n => Factorial(n));
Yo u c a n m a k e t h i s a p a r a l l e l q u e r y b y s i m p l y a d d i n g A s P a r a l l e l ( ) a s t h e
first method on the query:
var numsParallel = data.AsParallel().
Where(m => m < 150 ).Select(n => Factorial(n));
Of course, you can do the same kind of work with query syntax.
var nums = from n in data
where n < 150
select Factorial(n);
The Parallel version relies on putting AsParallel() on the data sequence:
var numsParallel = from n in data.AsParallel()
where n < 150
select Factorial(n);
The results are the same as with the method call version.
This first sample is very simple yet it does illustrate a few important
concepts used throughout PLINQ. AsParallel() is the method you call to
opt in to parallel execution of any query expression. Once you call
AsParallel(), subsequent operations will occur on multiple cores using
multiple threads. AsParallel() returns an IParallelEnumerable() rather than
an IEnumerable(). PLINQ is implemented as a set of extension methods
on IParallelEnumerable. They have almost exactly the same signatures as
the methods found in the Enumerable class that extends IEnumerable.
Simply substitute IParallelEnumerable for IEnumerable in both parame-
ters and return values. The advantage of this choice is that PLINQ follows
the same patterns that all LINQ providers follow. That makes PLINQ very
easy to learn. Everything you know about LINQ, in general, will apply to
PLINQ.
Of course, it's not quite that simple. This initial query is very easy to use
with PLINQ. It does not have any shared data. The order of the results
doesn't matter. That's why it is possible to get a speedup that's in direct
proportion to the number of cores in the machine upon which this code
 
Search WWH ::




Custom Search