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...
- Start off by creating a new method called
CancelParallelForEach()in theDemoclass, which takes two parameters. One is a collection ofList<string>, while the other is an integer specifying a timeout value. When the timeout value is exceeded, theParallel.ForEachloop must terminate:
public class Demo
{
public void CancelParallelForEach(List<string> intCollection,
int timeOut)
{
} ...