如果C#中的事件处理程序异常是安全的? [英] Should C# event handlers be exception safe?

查看:138
本文介绍了如果C#中的事件处理程序异常是安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个事件有多个处理程序,如果有事件处理程序抛出异常,然后不执行剩余的处理程序。

Assuming that one event has multiple handlers, if any of event handlers throw an exception then the remaining handlers are not executed.

这是否意味着事件处理程序不应该抛出?

Does this mean that event handlers should never throw?

推荐答案

由于调用的事件意味着,调用者有没有关于被叫知识:

Since invoking an event means that the caller has no knowledge about the callee:

  1. 调用的事件处理程序应该在任意例外面对强劲。一切都调用堆栈需要正确地收拾自己的烂摊子,万一东西完全出乎意料的发生。

  1. Invoking an event handler should be robust in the face of arbitrary exceptions. Everything up the call stack needs to clean up its own mess correctly, in case something completely unexpected occurs.

事件处理程序确实应该避免抛出异常。

Event handlers should really avoid throwing exceptions.

之类的东西空引用异常是在任何code真是不可原谅的,所以很明显,我们并不担心这一点。

Things like null reference exceptions are really inexcusable in any code, so obviously we aren't concerned about that.

之类的东西文件IO异常写入或读取文件时可以随时发生,所以我会避免以往的事件处理程序中做IO。如果是有意义的做IO在事件处理程序,那么它也使得senst处理处理程序中的IO异常了。难道不会传播是返回给调用者。寻找一些方法来处理它。

Things like file IO exceptions can always happen when writing or reading a file, so I would avoid ever doing IO within an event handler. If it makes sense to do IO in an event handler, then it also makes senst to handle the IO exceptions within the handler too. Don't propogate that back to the caller. Find some way to deal with it.

这篇关于如果C#中的事件处理程序异常是安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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