How to handle exceptions in Parallel.Foreach?

半世苍凉 提交于 2019-12-07 00:05:31

问题


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?

Best regards


回答1:


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?

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.



来源:https://stackoverflow.com/questions/40149119/how-to-handle-exceptions-in-parallel-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!