Should I always disconnect event handlers in the Dispose method?(我是否应该始终断开 Dispose 方法中的事件处理程序?)
问题描述
我使用 C# 工作,我的工作场所有一些代码标准.其中之一是我们连接的每个事件处理程序(例如 KeyDown)必须在 Dispose 方法中断开连接.有什么好的理由吗?
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 just 以删除事件处理程序.
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 方法中的事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我是否应该始终断开 Dispose 方法中的事件处理程序?
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
