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) {
} }
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, break out of the loop:
var timer = Stopwatch.StartNew(); Parallel.ForEach(intCollection, (integer, state) => { Thread.Sleep(1000); if (timer.Elapsed.Seconds > timeOut) { WriteLine($"Terminate thread {Thread.CurrentThread .ManagedThreadId}. Elapsed time { timer.Elapsed.Seconds} seconds"); state.Break(); } WriteLine($"Processing item {integer} on thread {Thread.CurrentThread.ManagedThreadId}"); });
In the console application, create the List<string> object and add 1000 items to it. Call the CancelParallelForEach() method with a timeout of only 5 seconds:
List<string> integerList = new List<string>(); for (int i = 0; i <= 1000; i++) { integerList.Add(i.ToString()); }