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!

‘System.Threading.Tasks.Task’ does not contain a definition for ‘Result’

‘System.Threading.Tasks.Task’ does not contain a definition for ‘Result’ and no extension method ‘Result’ accepting a first argument of type ‘System.Threading.Tasks.Task’ could be found (are you missing a using directive or an assembly reference?)

This is an annoying error that I spent about an hour trying to source. It turned out, I had a bad parameter in the ContinueWith. Stupid TPL. Stupid Compiler.

.ContinueWith(task => { DoWork(task.Result); },MyScheduler);

So, make sure your parameters are correct. i.e. ensure that you have an actual taskscheduler instead of a dispatcher or whatever. Happy Coding!