Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment index on a particular value in Parallel.For?

I want to increment an index on a particular value, for example 2:

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

How do I do the same using the Parallel class, like:

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

Edit

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

like image 605
oleksii Avatar asked Nov 30 '11 17:11

oleksii


1 Answers

Another approach would be to use where clause:

Parallel.ForEach(Enumerable.Range(0, 10).Where(i => i % 2 == 0), i =>
{
    Console.WriteLine(i);
});
like image 127
oleksii Avatar answered Sep 19 '22 12:09

oleksii