[英]Aborting Parallel.Foreach
I'm using Parallel.ForEach
for achieving parallelism, I was wondering is there any way that I can stop the execution of Parallel.ForEach
once any one the requests complete. 我正在使用
Parallel.ForEach
实现并行性,我想知道有什么方法可以在任何一个请求完成后停止执行Parallel.ForEach
。 For example consider the following code: 例如,考虑以下代码:
IEnumerable<string> myList = new List<string>() { "admin", "admin2", "admin3" };
CancellationTokenSource _tokenSource = new CancellationTokenSource();
Parallel.ForEach(myList,
admin_name =>
{
Console.WriteLine(admin_name);
});
The above code prints admin
, admin2
and admin3
. 上面的代码显示
admin
, admin2
和admin3
。 I want to stop further execution if any of the admin names is printed. 如果要打印任何管理员名称,我想停止进一步执行。
Is this achievable? 这可以实现吗? Or is there any work around available?
还是有其他解决方法?
I am open to suggestions and improvement. 我愿意提出建议和改进。
There is an overload of Parallel.ForEach
which passes a ParallelLoopState
to your delegate, this can be use to break out of the Parallel.ForEach
, ie: 有过载
Parallel.ForEach
它传递一个ParallelLoopState
到您的代理,这样可以利用打出来的的Parallel.ForEach
,即:
Parallel.ForEach(myList, (admin_name, state) =>
{
Console.WriteLine(admin_name);
// Stop other iterations
state.Stop();
});
What you will need to bear in mind is that this will not be atomic, other delegates which have already started will continue to execute, unless they explicitly check state.IsStopped
. 您需要记住的是,这将不是原子的,已经启动的其他委托将继续执行,除非他们明确检查
state.IsStopped
。
Instead of ParallelLoopState.Stop()
you may desire ParallelLoopState.Break()
. 代替
ParallelLoopState.Stop()
您可能希望使用ParallelLoopState.Break()
。
Some further information about Stop()
and Break()
can be found at How to: Stop or Break from a Parallel.For Loop . 有关
Stop()
和Break()
更多信息,请参见如何:从Parallel.For循环停止或中断 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.