Reverse Loop using Parallel.For RRS feed

  • Question

  • Hello everybody, I want to write a reverse for loop using parallel extension. I used this overload:
    Parallel.For(max, min, -1, i =>{
    //blah blah blah

    But it throws this exception:
    System.ArgumentOutOfRangeException was unhandled
      Message="Specified argument was out of the range of valid values.\r\nParameter name: step"
           at System.Threading.Parallel.For(Int32 fromInclusive, Int32 toExclusive, Int32 step, Action`1 body)
           at ConsoleApplication1.Program.Main(String[] args) in C:\Projects\Assignment1\ConsoleApplication1\ConsoleApplication1\Program.cs:line 29
           at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()

    How can I do this? Thanks in advance

    Saturday, February 28, 2009 6:03 PM


  • Parallel.For supports iteration in the positive direction.  To iterate in reverse, you can do something like the following:

    Parallel.For(0, max - min, pos =>
        int i = max - pos;
        ... // use i, which will iterate [max,min).

    As an example, if min is -5 and max is 5, max-min will be 10, and thus the loop will iterate from 0 to 9, inclusive.  The i value will be set to max minus the iteration variable, which means it'll get the values (5-0)==5, (5-1)==4, ..., (5-9)==-4, and thus you'll be iterating from max (inclusive) to min (exclusive).  If you want to iterate (max,min] instead of [max,min), you could change it to:

    Parallel.For(0, max - min, pos =>
        int i = max - pos - 1;
        ... // use i, which will iterate (max,min].

    Saturday, February 28, 2009 7:31 PM