取消注册所有事件以释放内存 [英] Unregistering all events to release memory

查看:123
本文介绍了取消注册所有事件以释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以编辑产品信息的程序。我注意到在关闭编辑表单后并没有释放内存。经过一番研究,我偶然发现了这个问题,提到问题可能是它挂在事件订阅。



这对我来说很有意义,因为这个表单有大约100多个控件,其中许多是自定义的,由他们的父控件订阅的自定义事件。这将创建一个相当大的事件订阅层次结构。所以我寻找一种方法来发布这些,并发现这个它允许您取消订阅该事件。



问题是,我有大量订阅。我真的需要手动取消订阅每个事件,一个接一个地表示,或者至少有一种方式一举发布,还是循环?

解决方案

记住: + = 的LEFT上的对象保持包含 code> + = 。也就是说,即使处理事件的对象(如表单)被处理,引发的对象仍然保持处理事件的对象。 / p>

所以你需要确保的是所有的事件提升者已经消失了。



但是,如果所有事件提升者恰好是在订阅这些事件的相同 Form 类中的控件,您将不需要手动解除所有事件表单关闭时的处理程序。



这是因为引发已订阅的表单的事件的控件与表单本身具有相同的生命周期。



如果您订阅了一个对象所生成的事件,该对象的生命周期长于正在订阅的对象,则只需担心。然后订阅对象(表单)需要取消订阅(表单)。


I have a program which allows the editing of product information. I noticed that it was not releasing memory after closing the editing forms. After some research I stumbled upon this question which mentions that the problem may be that it is hanging on to event subscriptions.

That made sense to me because this form has about 100+ controls on it, many of which are custom with custom events which are subscribed to by their parent controls. This creates a pretty large hierarchy of event subscriptions. So I looked for a way to release these and found this which allows you to unsubscribe from that event.

The problem is, I have a ton of subscriptions. Do I really have to manually unsubscribe from each event one by one on form close, or is there at least a way to release them in one fell swoop, or loop through them?

解决方案

Remember this: The object on the LEFT of the += keeps alive the object containing the method on the RIGHT of the +=. That is, the object that raises the event keeps alive the object that handles the event, even if the object (such as a form) that handles the event is disposed.

So the thing you need to ensure is that all the event-raisers have gone away.

However, if all the event-raisers happen to be controls in the same Form class that subscribes to those events, you will not need to manually unhook all the event handlers when the form is closed.

This is because the controls that raise the events to which to form has subscribed have the same lifetime as the form itself.

You only need to worry if you subscribe to events raised by an object that has a longer lifetime than the object that is subscribing. Then the subscribing object (the form) would need to unsubscribe when it (the form) is disposed.

这篇关于取消注册所有事件以释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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