Parallel.Foreach 异常和取消
我试图找出 Parallel.Foreach 的异常和取消是如何工作的。所有示例似乎都涉及任务。
Parallel.Foreach
中出现异常会发生什么?
- 我是否将整个循环包装在 try/catch (
AggregateException
) 中? - 循环中的所有其他任务(甚至尚未开始的任务)是否会在捕获异常之前运行完成?
对于 CancellationToken
也有同样的问题。
I have tried to find out how exceptions and cancel work for Parallel.Foreach
. All examples seems to deal with Tasks.
What happens on an exception in Parallel.Foreach
?
- Do I wrap the entire loop in try/catch (
AggregateException
)? - Will all other tasks in the loop, even tasks not started yet, run to completion before the exception is caught?
Same questions for CancellationToken
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简而言之,每个循环中的异常都会聚合并呈现在
AggregateException
下。每当发生异常时,允许完成已启动的循环,但不会启动更多循环。ForEach
确实有很多 重载,允许本地初始化和初始化。 finally 块和主体操作也采用 ParallelLoopState该循环体代码可用于检查另一个循环上是否发生异常,然后在需要时自行中断它。请参阅本文 提供附加信息
In short, exception in each loop is aggregated and presented under
AggregateException
. Whenever exception occurs, loops that are started are allowed to complete but no further loops will be started.ForEach
does have many overloads that allow one to have local init & finally blocks and body action also takes ParallelLoopState that loop body code can use to check for exception occurrence on another loop and then break it self cooperatively if needed.See this article that provides additional information