How it works...

You can see from the console window output that, as soon as the elapsed time exceeded the timeout value, the parallel loop was notified to cease the execution of iterations beyond the current iteration at the system's earliest convenience. Having this kind of control over the Parallel.ForEach loop allows developers to avoid runaway loops, and gives the user control to cancel a loop operation by clicking on a button or automatically having the application terminate when the timeout value has been reached.

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.