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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With