Cancelling a parallel foreach loop

When dealing with parallel foreach loops, the obvious question is how one would terminate the loop prematurely based on a certain condition, such as a timeout. As it turns out, the parallel foreach loop is quite easy to terminate prematurely.

Getting ready

We will create a method that takes a collection of items and loops through this collection in a parallel foreach loop. It will also be aware of a timeout value that, if exceeded, will terminate the loop and exit the method.

How to do it…

  1. Start off by creating a new method called CancelParallelForEach() in the Recipes class, which takes two parameters. One is a collection of List<string>, while the other is an integer specifying a timeout value. When the timeout ...

Get C# Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.