I\'m just looking in to the new .NET 4.0 features. With that, I\'m attempting a simple calculation using Parallel.For
and a normal for(x;x;x)
loop.
An important point no-one seems to have mentioned: For data-parallel operations (such as the OP's), it is often better (in terms of both efficiency and simplicity) to use PLINQ instead of the Parallel
class. The OP's code is actually trivial to parallelize:
long sum = Enumerable.Range(1, 10000).AsParallel().Sum();
The above snippet uses the ParallelEnumerable.Sum method, although one could also use Aggregate for more general scenarios. Refer to the Parallel Loops chapter for an explanation of these approaches.