How to do it...

  1. Start off by creating a new method called CancelParallelForEach() in the Demo 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 Demo         {           public void CancelParallelForEach(List<string> intCollection,             int timeOut)           {                      }             }
  1. Inside the CancelParallelForEach() method, add a timer to keep track of the elapsed time. This will signal the loop that the timeout threshold has been exceeded and that the loop needs to exit. Create a Parallel.ForEach method defining a state. In each iteration, check the elapsed time against the timeout, and if the time is exceeded, ...

Get C# 7 and .NET Core 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.