事件处理程序中的异常管理实践 [英] Exception management practices inside event handlers

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

问题描述

.NET 4.0,C#

.NET 4.0, C#

我正在尝试向项目中添加一些异常管理框架。

I'm trying to add some exception management framework to my project. The framework publishes exceptions to a database if able.

我已经对异常处理进行了大量研究,但在理解如何处理异常方面遇到了一些麻烦m应该处理事件处理程序内部发生的异常(即timer.elapsed或async回调)。每个事件处理程序都应该有一个try catch块吗?

I've done a good amount of research on exception handling but I'm having a bit of trouble understanding how I'm supposed to handle exceptions which occur inside event handlers (i.e. a timer.elapsed or an async callback). Should each event handler have a try catch block?

谢谢!

推荐答案

事件处理程序的主体中应该始终具有 try..catch..finally 块,以防止事件处理程序传播异常。同样,事件处理程序有望快速执行,因此避免在事件处理程序本身内部执行昂贵的IO或数据库操作。

The event handler should always have a try..catch..finally block in its body to prevent the event handler from propagating the exception. Also, event handlers are expected to execute quickly so avoid performing expensive IO or database operations inside the event handler itself.

此外,您可以拥有类似错误,用于向事件的订户指示发生了错误(在异步调用的情况下)。

Furthermore, you can have a property like Error to indicate to the subscribers of the event that an error has occurred (in case of an async call).

更多信息

  • C# event fundamentals and exception handling in multicast delegates
  • top-level exception handling with event handlers in c#
  • Should C# event handlers be exception safe?
  • Async command pattern - exception handling
  • Best Practices for Implementing the Event-based Asynchronous Pattern

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

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