Parallel.For(): Update variable outside of loop

前端 未结 7 2055
面向向阳花
面向向阳花 2020-11-29 22:20

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.

相关标签:
7条回答
  • 2020-11-29 23:08

    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.

    0 讨论(0)
提交回复
热议问题