John Egbert
John Egbert

Reputation: 5766

Is there an equivalent to 'continue' in a Parallel.ForEach?

I am porting some code to Parallel.ForEach and got an error with a continue I have in the code. Is there something equivalent I can use in a Parallel.ForEach functionally equivalent to continue in a foreach loop?

Parallel.ForEach(items, parallelOptions, item =>
{
    if (!isTrue)
        continue;
});

Upvotes: 335

Views: 95658

Answers (3)

Slipoch
Slipoch

Reputation: 785

Simply refactor your code, there is little reason to use a continue in high level languages.

Your example would indicate something like:

Parallel.ForEach(items, parallelOptions, item =>
{
    //Code that has to be processed for all entries

    if (!isTrue) {
        continue;
    }

    //Code that is only done to elements passing a certain test
});

The danger is when the code above your continue gets larger and you miss the continue when you come back in 6 months to make some changes. (I also always put in braces around any if output to protect against additions inside the if).

How I would do it.

Parallel.ForEach(items, parallelOptions, item =>
{
    //Code that has to be processed for all entries

    if (isTrue) {
        //Code that is only done to elements passing a certain test
    }
});

So the code above doesn't use or save any more system resources but it does mean if you are quickly scanning the code you will immediately see that the code only done to some elements is obviously inside a conditional due to the tabbed in nature of it.

If you are not putting any code above the continue then it is pointless (and a waste of cpu cycles & RAM) to have it in there, in that case I would refactor to something like the following:

Parallel.ForEach(items.Where(x => x.IsTrue()), parallelOptions, item =>
{
    //Code that is only done to elements passing a certain test
});

Now in the above case you may not want to use a static, modern C# should be able to call a static extension from a different thread to main, it just means instead of storing a new copy of the function on every object, you store it once and the process is cached in every thread that is opened by your program.

Instead you could be looking at a Bool on the object, or if you want to make absolutely sure the check on whether to include this item in the processing is done or not, then the second last example is exactly what you would use.

Upvotes: -4

Taran
Taran

Reputation: 3221

When you converted your loop into a compatible definition for the Parallel.Foreach logic, you ended up making the statement body a lambda. Well, that is an action that gets called by the Parallel function.

So, replace continue with return, and break with Stop() or Break() statements.

Upvotes: 45

dave
dave

Reputation: 13280

return;

(the body is just a function called for each item)

Upvotes: 559

Related Questions