不注销事件处理程序是不是很糟糕? [英] Is it bad to not unregister event handlers?

查看:103
本文介绍了不注销事件处理程序是不是很糟糕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个应用程序只有几个事件处理程序被注册(并且使用事件的对象不会被处理,直到应用程序关闭),我真的需要担心取消注册这些处理程序吗?唯一可以看到的很好的理由是,如果事件被触发,你不需要关心(也就是说,你有多个处理程序注册到一个事件),可能会有一点额外的开销。还有其他好的理由吗?任何人遇到重大问题,因为他们没有注销活动?

解决方案

如果您有 A 发布一个事件,并且 B 订阅一个事件(处理程序),那么只有一个问题不取消订阅如果 A 将比 B 生活的时间长得多。基本上,事件订阅意味着 A 仍然可以看到 B ,所以会阻止它被垃圾回收,即使你忘记了它(也许 Disposed()它),仍然会发生事件。



例如,如果 A 是一个静态事件,并且您的应用程序在 B die之后运行一段时间,这是一个问题...



请注意,请问如下:


<如果B生活比A长得多,B会不会收集垃圾?


而且答案是没有。 B通过事件没有提到A; A将正常收集


If I have an application with only a few event handlers registered (and the objects using the events are not disposed until the application is closed), do I really need to worry about unregistering those handlers? The only good reason I could see is that there might be a little extra overhead if events are being fired that you dont necessarly care about (i.e you have multiple handlers registered to one event). Is there any other good reason to? Anyone run into major issues because they didnt unregister events?

解决方案

If you have A publishing an event, and B subscribing to an event (the handler), then it is only a problem not to unsubscribe if A is going to live a lot longer than B. Basically, the event subscription means that A can still see B, so would prevent it from being garbage collected, and would still fire events on it even if you've forgotten about it (and perhaps Disposed() it).

For example, this is a problem if A is a static event, and your app runs for a while after B dies...

It is important to note, one might ask the following:

if B lives a lot longer than A, will B keep A from being garbage collected?

And the answer to that is "no". B has no reference to A through the event; A will be collected as normal

这篇关于不注销事件处理程序是不是很糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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