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, 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}");
});
  1. 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());
}

Demo oRecipe = new Demo();
oRecipe.CancelParallelForEach(integerList, 5);
WriteLine($"Parallel.ForEach loop terminated");
ReadLine();
  1. Run your console application and review the output results:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.142.166