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

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

问题描述

我的工作在C#和我的工作有一定的code标准。其中之一是,每个事件处理程序,我们连接(如的KeyDown )必须在处置方法被断开。有没有什么好的原因是什么?

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.

这是那些民间传说成长起来的话题之一。你真的只需要想一想在正常条件:发布者(如按钮)引用了该用户。如果同时发布和订阅者将有资格进行垃圾回收的同时反正(这是常见的),或者如果发布者将有资格进行垃圾回收的前面的,那么就没有GC的问题。

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.

静态事件导致GC问题,因为他们是一个有效的无限长的寿命出版商 - 我会劝阻静态事件完全是,在可能的情况。 (我很少发现它们非常有用。)

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.)

另一个可能的问题是,如果你明确要停止监听事件,因为你的对象会表现不好,如果引发事件(例如,它会尝试写一个封闭的流)。在这种情况下,是的,你应该删除处理。这是最有可能的情况下,你的类实现的IDisposable 了。这将是不寻常的 - 尽管不是不可能 - 它是值得实施的IDisposable 只是的删除的事件处理程序

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天全站免登陆