Search code examples
c#for-loopparallel-processingtask-parallel-libraryparallel.for

Parallel.For using step != 1


Is there any way to achieve the Parallel.For version of this for loop?

for (int i = 0; i < 100; i += 2) { DoStuff(i); }

I don't see an overload which accepts a step parameter, though I can't think of any reason this would be logically impossible.

The accepted answer to this and this question suggests using Parallel.ForEach on a range of ints generated using Enumerable.Range, but in my case I am using thread local data so Parallel.ForEach is not an option.

Another option is to just check if i % 2 == 0 in the body of my loop and return, but this still executes the thread local data intializer Func and finalizer Func. 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;
        );
    }
);

Solution

  • Here's a hint:

    for (int j = 0; j < 50; j++) { i = 2*j; DoStuff(); }
    

    In general, see if you can figure out the number of iterations and a transformation from iteration number to the variable value.