Parallel. To use the step! = 1

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; ); } ); 
+8
c # parallel-processing for-loop task-parallel-library
source share
4 answers

Here is a hint:

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

In general, see if you can determine the number of iterations and the conversion from the iteration number to the value of the variable.

+14
source share

Ben's suggestion is very good for a constant move, for example. +2, +3, etc.

Alternatively (if your step is random) you can use Parallel.ForEach , for example.

 int[] input = { 1, 3, 4, 5, 7, 10, 20, 25 }; Parallel.ForEach(input, () => new Bar(), //thread local data initialize (i, state, local) => //loop body { // your code }, (local) => //thread local data post-action { // your code } 

The variable i will receive data from the input array. You can replace input with Enumerable.Range (or combine it with With , etc.)

This will work just fine if you want to get only the prime number in variable i .

+3
source share

Here's another way to handle step indexes

 private void ParallelForEachProcessSteppedIndexes() { Parallel.ForEach(SteppedIterator(0, 100, 2), (index) => DoStuff(index)); } private static IEnumerable<int> SteppedIterator(int startIndex, int endIndex, int stepSize) { for (int i = startIndex; i < endIndex; i = i + stepSize) { yield return i; } } 
+3
source share

Toan's answer worked for me after converting to the new Iterator VB.NET function

 Private Sub LoopExample() Parallel.ForEach(SteppedIterator(1,100,5), AddressOf Test) End Sub Private Iterator Function SteppedIterator(startIndex As Integer, endIndex As Integer, stepSize As Integer) As IEnumerable(Of Integer) For i As Integer = startIndex To endIndex Step stepSize Yield i Next End Function Private Sub Test(i As Integer, state As ParallelLoopState, index As Long) Debug.WriteLine(i.ToString) End Sub 
0
source share

All Articles