Changing the incremental value of a C # Parallel.For loop

I want to convert a for loop that increments the iterator by 2 each pass into a Parallel For loop using TPL. The data in no way depends on the order or restrictions, but I want to process the data only in every other element of my source array (which is _Datalist in the code below), therefore, it needs to be increased by 2.

My For Loop:

for (int i = 1; i < _DataList.Length - 1; i += 2) { // Do work for _DataList[i] } 

Is it possible to indicate a parallel loop that I want to increase by two instead of one?

Here's Parallel Loop, but obviously, I only increment by 1 every iteration:

  Task.Factory.StartNew(() => Parallel.For(1, _DataList.Length, i => { // do work for _DataList[i] }) ); 

I could tell the inner body of the loop to ignore the odd values ​​of i, but this is like litle messy - is there a way to do this in the loop initialization somehow?

+5
c # parallel-processing task-parallel-library
source share
4 answers

What about:

 var odds = Enumerable.Range(1, _DataList.Length).Where(i => i % 2 != 0); Task.Factory.StartNew(() => Parallel.ForEach(odds, i => { // do work for _DataList[i] }) ); 
+10
source share

You can halve the number of steps and double the indices:

 Parallel.For(0, _DataList.Length / 2, i => { // do work for _DataList[2 * i] }); 
+10
source share

Darin Dimitrov’s answer shows a simple way to achieve this.

However, this was not added, as it is usually a sign that the cycle bodies are not really different. In most cases, the need to use a different gain value usually arises only when processing in a certain order or other problems that can lead to parallelization to create race conditions are necessary.

0
source share

Just skip the even numbers.

 Task.Factory.StartNew(() => Parallel.For(1, _DataList.Length, i => { if(i % 2 == 0) { // do work for } }) ); 
-one
source share

All Articles