Is there a way to reach the Parallel.For version of this for loop?
for (int i = 0; i < 100; i += 2) { DoStuff(i); }
I do not see the overload that accepts the step parameter, although I cannot think of any reason that this would be logically impossible.
In the accepted answer to this and this, it is suggested to use Parallel.ForEach in the int range generated using Enumerable.Range , but in my case I use local stream data , so Parallel.ForEach not an option .
Another option is to simply check if i % 2 == 0 in the body of my loop and return , but this still localizes the local Func and finalizer Func stream data. Below is a code snippet demonstrating this option:
Parallel.For<Bar>(0, limit, () => new Bar(), //thread local data initialize (i, state, local) => //loop body { if (i % 2 != 0) return local; local.foo += DoStuff(i); return local; }, (local) => //thread local data post-action { lock (loopLocker) { globalData.foo += local.foo; ); } );
c # parallel-processing for-loop task-parallel-library
Rotem
source share