What would be the most effective way to pause and stop (before it ends) parallel.foreach?
Parallel.ForEach(list, (item) =>
{
doStuff(item);
});
To be able to stop a Parallel.ForEach
, you can use one of the overloads that accepts a ParallelOptions parameter, and include a CancellationToken in those options.
See Cancellation for more details.
As for pausing, I can't think why you'd want to do that, in general. You might be looking for a Barrier (which is used to coordinate efforts between multiple threads, say if they all need to complete part A before continuing to part B), but I wouldn't think that you'd use that with Parallel.ForEach
, since you don't know how many participants there will be.