问题描述
我有看起来像这样的代码:
I've got code which looks something like this:
Parallel.Foreach(ItemSource(),(item)=>DoSomething(item));
ItemSource()
产生无限的项目流.
我希望一旦满足某些条件就退出循环,我希望这样做不会在DoSomething中引发异常(我认为这种方法是不好的编程风格).
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).
理想情况下,会有诸如cancelleToken之类的东西.我会在一个或多个线程中调用cancelToken.Activate(),此后parallel.foreach将停止创建新线程,并且在最后一个线程退出后,该函数将返回.
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.
这是否可以在Parallel.ForEach的c#中完成,还是应该使用线程insteag?
Is this possible to do in c# with Parallel.ForEach, or should I use threads insteag?
更新这是微软建议的方式我做到了:
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.
推荐答案
在Parallel.ForEach中,有一个创建ParallelLoopState的选项,该状态使您可以打破循环:
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();
}
在此处 http://msdn.microsoft.com/es-es/library/system.threading.tasks.parallelloopstate.aspx
这篇关于如何正确取消Parallel.Foreach?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!