我应该总是在 Dispose 方法中断开事件处理程序吗? [英] Should I always disconnect event handlers in the Dispose method?

查看:33
本文介绍了我应该总是在 Dispose 方法中断开事件处理程序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C# 中工作,我的工作场所有一些代码标准.其中之一是我们连接的每个事件处理程序(例如 KeyDown)必须在 Dispose 方法中断开连接.有什么好的理由吗?

解决方案

除非您希望事件的发布者比订阅者的生命周期更长,否则没有理由删除事件处理程序,不.

这是民间传说已经成长起来的主题之一.你真的只需要用正常的术语来考虑它:发布者(例如按钮)有一个对订阅者的引用.如果发布者和订阅者无论如何都可以同时进行垃圾回收(这很常见),或者如果发布者更早有资格进行垃圾回收,那么就不存在 GC 问题.>

静态事件会导致 GC 问题,因为它们实际上是一个无限长的发布者 - 我会在可能的情况下完全阻止静态事件.(我很少发现它们有用.)

另一个可能的问题是,如果您明确想要停止侦听事件,因为如果引发事件(例如,它会尝试写入关闭的流),您的对象将出现异常行为.在这种情况下,是的,您应该删除处理程序.这很可能是在您的类已经实现了 IDisposable 的情况下.实现IDisposable只是来删除事件处理程序是不寻常的——尽管并非不可能——这是值得的.

I'm working in C# and my workplace has some code standards. One of them is that each event handler we connect (such as KeyDown) must be disconnected in the Dispose method. Is there any good reason for that?

解决方案

Unless you expect the publisher of the event to outlive the subscriber, there's no reason to remove the event handler, no.

This is one of those topics where folk lore has grown up. You really just need to think about it in normal terms: the publisher (e.g. the button) has a reference to the subscriber. If both the publisher and the subscriber will be eligible for garbage collection at the same time anyway (as is common) or if the publisher will be eligible for garbage collection earlier, then there's no GC issue.

Static events cause a GC problem because they're effectively an infinitely-long-lived publisher - I would discourage static events entirely, where possible. (I very rarely find them useful.)

The other possible issue is if you explicitly want to stop listening for events because your object will misbehave if the event is raised (e.g. it will try to write to a closed stream). In that case, yes, you should remove the handler. That's most likely to be in the case where your class implements IDisposable already. It would be unusual - though not impossible - for it to be worth implementing IDisposable just to remove event handlers.

这篇关于我应该总是在 Dispose 方法中断开事件处理程序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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