如何在Parallel.Foreach中处理异常? [英] How to handle exceptions in Parallel.Foreach?

查看:583
本文介绍了如何在Parallel.Foreach中处理异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有一个parallel.Foreach循环,我想知道如何处理异常。我应该在循环内捕获并处理(例如写入日志)异常,还是在外部捕获聚集异常-在try / catch中捕获循环?

I have a parallel.Foreach loop in my code and I am wondering how to handle exceptions. Should I catch and handle(e.g write to log) exceptions inside the loop or should I catch aggregate exception outside - encapuslate the loop in try/catch?

最诚挚的问候

推荐答案


我应该在循环内捕获并处理异常,还是应该在

Should I catch and handle exceptions inside the loop or should I catch aggregate exception outside

这两个在功能上并不等效。两者都可以并且可以以不同的方式来完成。

Those two are not functionally equivalent. Both can be done, and in different ways.

但是更基本的问题是:当一个或多个迭代遇到异常时,是否要处理其余项?

But the more fundamental question is: when one or more iterations suffer an exception, do you want the remaining items to be processed or not?

如果是,则在循环中处理它们,可能像在 MSDN示例

如果没有,则只需尝试一下/抓住Parallel循环本身即可。

If yes, then handle them inside the loop, possibly storing them like in the MSDN example.
If not, just put a try/catch around the Parallel loop itself.

这篇关于如何在Parallel.Foreach中处理异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆