Parallel.For(): Update variable outside of loop

前端 未结 7 2096
面向向阳花
面向向阳花 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 22:56

    I think it's important to distinguish that this loop is not capable of being partitioned for parallelism, because as has been mentioned above each iteration of the loop is dependent on the prior. The parallel for is designed for explicitly parallel tasks, such as pixel scaling etc. because each iteration of the loop cannot have data dependencies outside its iteration.

    Parallel.For(0, input.length, x =>
    {
        output[x] = input[x] * scalingFactor;
    });
    

    The above an example of code that allows for easy partitioning for parallelism. However a word of warning, parallelism comes with a cost, even the loop I used as an example above is far far too simple to bother with a parallel for because the set up time takes longer than the time saved via parallelism.

提交回复
热议问题