Parallel.Foreach 异常和取消

发布于 2024-10-19 00:05:29 字数 280 浏览 9 评论 0原文

我试图找出 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

惯饮孤独 2024-10-26 00:05:29

简而言之,每个循环中的异常都会聚合并呈现在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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文