oleksii
oleksii

Reputation: 35905

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.

Upvotes: 9

Views: 11081

Answers (5)

oleksii
oleksii

Reputation: 35905

Another approach would be to use where clause:

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

Upvotes: 2

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41757

The implicit assumption in the first loop is that j is incremented sequentially.
In the second example the value of j can be any of 0 -> 9 in any of the loops.

You can achieve the same behaviour by the following:

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

Upvotes: 11

Jon Egerton
Jon Egerton

Reputation: 41549

If you're trying to do the equivalent of step size, then this post may help:

Parallel.For step size

If you just want to omit a certain value you'll just need to ignore it.

The Parallel.For won't run the items in order, so i += 2 is meaningless.

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273244

A simple adaptation:

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

In other words, you can almost alays find a projection from the sequential i to the desired loopvalue (j). rbitrary sr

The other stake-holder here is the partitioner, you can't expect it to deal with arbitrary sequences.

Upvotes: 2

Lukazoid
Lukazoid

Reputation: 19416

It appears like you want to iterate over the values 0 to 10, with an increment of 2. Why not implement it like the following:

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

Upvotes: 3

Related Questions