-
Book Overview & Buying
-
Table Of Contents
C# Programming Cookbook
By :
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.
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.
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 value is exceeded, the Parallel.ForEach loop must terminate:
public class Recipes
{
public void CancelParallelForEach(List<string> intCollection, int timeOut)
{
}
}Inside the CancelParallelForEach() method, add a...