Break Parallel Foreach Earlier
Use the ParallelLoopState.Break or ParallelLoopState.Stop method to end parallel foreach loop:
public void BreakParallelForeachEarlier()
{
var list = new List<Int32>();
for (var i = 0; i < 100; ++i)
list.Add(i);
var startTime = DateTime.Now;
var maxRunTimeInMs = 2500;
Parallel.ForEach(list, (elem, state) =>
{
Console.WriteLine("Running for {0}", elem);
Thread.Sleep(1000 + elem); // Running exhausting algorithm
var duration = (DateTime.Now - startTime).TotalMilliseconds;
if (duration > maxRunTimeInMs)
{
Console.WriteLine("Exiting the parallel foreach block...");
state.Break();
}
});
}
added 9 years 7 months ago