Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly cancel Parallel.Foreach?

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.

like image 979
Arsen Zahray Avatar asked Oct 10 '13 19:10

Arsen Zahray


2 Answers

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

like image 106
Gonzix Avatar answered Sep 28 '22 03:09

Gonzix


It's not necessary to call ThrowIfCancellationRequested(), because Parallel.For()/Parallel.ForEach() already does that internally. That Microsoft Docs page will be updated soon - GitHub issue

like image 42
VladStepu2001 Avatar answered Sep 28 '22 02:09

VladStepu2001