Monna L Monna L - 5 days ago 4
C# Question

Change for loop to Parallel.For loop

I can change my loop

for (int i = 0; i < something; i++)


to:

Parallel.For(0, something, i =>


But how to do this with this loop?:

for (i = 3; i <= something / 2; i = i + 2)


Thanks for answers.

Answer

The third parameter is a delegate. So every iteration you could specify what your indexing variable shall do inside the delegate.

Here is a brief example:

int something = 16;

List<int> numbers = Enumerable.Range(0, 20).ToList();

Parallel.For(3, something / 2, i => { i += 2; Console.WriteLine(numbers[i]); });