Continue or Break using Parallel.ForEach

You might be converting your normal foreach loop over to use the Parallel.ForEach syntax to improve performance in a thread safe loop.

You also probably have some break and continue statements.

Well, it took me a few to figure out how to deal with these. Turns out, it is simple.

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

So, pretend it is a method. When you are done, you just return. So, replace your continues and breaks with return statements.

Easy, right? Requires the mental shift from built in operators, to library function calls.

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *