How to increase the index by a certain value in Parallel.For?

I want to increase the index by a specific value, for example 2:

for (int i = 0; i < 10; i+=2) { Console.WriteLine(i); } 

How can I do the same with the Parallel class, for example:

 Parallel.For(0, 10, i => { Console.WriteLine(i); i += 2; //this a naïve assumption, it not working }); 

Edit

I would like the Parallel loop to run only 5 operations (as sequential for) and the order does not matter to me.

+7
source share
5 answers

The implicit assumption in the first cycle is that j sequentially increases.
In the second example, the value of j can be any of 0 → 9 in any of the cycles.

You can achieve the same behavior as follows:

 Parallel.ForEach(Enumerable.Range(0, 5).Select(i => i*2), i => { Console.WriteLine(i); }); 
+7
source

It looks like you want to iterate over values ​​from 0 to 10 in increments of 2. Why not implement it as shown below:

 Parallel.For(0, 5, i => { int value = i * 2; Console.WriteLine(value); }); 
+3
source

If you are trying to make a step size equivalent, this post may help:

Parallel. For step size

If you just want to omit a specific value, you just need to ignore it.

Parallel.For will not start elements in order, so i += 2 does not make sense.

+3
source

Simple adaptation:

 Parallel.For(0, 5, i => { int j = i * 2; Console.WriteLine(j); // i += 2; //this a naïve assumption, it not working }); 

In other words, you can almost find the projection from sequential i to the desired value of the loop ( j ). rbitrary sr

Another bet holder here is a separator; you cannot expect it to deal with arbitrary sequences.

+2
source

Another approach would be to use the where clause:

 Parallel.ForEach(Enumerable.Range(0, 10).Where(i => i % 2 == 0), i => { Console.WriteLine(i); }); 
+1
source

All Articles