How do I properly cancel Parallel.Foreach?

安稳与你 提交于 2020-12-03 17:12:39

问题


I've got code which looks something like this:

Parallel.Foreach(ItemSource(),(item)=>DoSomething(item));

ItemSource() produces an infinite stream of items.

I want the loop to exit once some condition has been met, and I'd rather do it without throwing an exception in DoSomething (I consider this approach a bad programming style).

Ideally, there would be something like cancellationToken. I would call cancellationToken.Activate() in one or more threads, after which parallel.foreach would stop creating new threads and after the last thread has exited, the function would return.

Is this possible to do in c# with Parallel.ForEach, or should I use threads insteag?

UPDATE Here's how microsoft suggests I do it:

        try
        {
            Parallel.ForEach(nums, po, (num) =>
            {
                double d = Math.Sqrt(num);
                Console.WriteLine("{0} on {1}", d, Thread.CurrentThread.ManagedThreadId);
                po.CancellationToken.ThrowIfCancellationRequested();
            });
        }
        catch (OperationCanceledException e)
        {
            Console.WriteLine(e.Message);
        }

I don't like this approach, because it involves throwing exception inside the delegate.


回答1:


In Parallel.ForEach there is an option to create a ParallelLoopState this state allows you to break the loop:

ParallelOptions po = new ParallelOptions();
po.MaxDegreeOfParallelism = Constants.MaxParallelProcesses;
var drc = Companies.AsEnumerable();

Parallel.ForEach(drc, po, (drcCompany, loopState) =>
{
    //do stuff here
    if(YourBreakCondition) loopState.Break();
}

Check the ParallelLoopState here http://msdn.microsoft.com/es-es/library/system.threading.tasks.parallelloopstate.aspx



来源:https://stackoverflow.com/questions/19304300/how-do-i-properly-cancel-parallel-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!