Parallel.Foreach c# Pause And Stop Function?

前端 未结 2 833
醉梦人生
醉梦人生 2021-01-18 08:57

What would be the most effective way to pause and stop (before it ends) parallel.foreach?

Parallel.ForEach(list, (item) =>
{
    doStuff(item);
});
         


        
2条回答
  •  野的像风
    2021-01-18 09:11

    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.

提交回复
热议问题