有趣的事件"配置"行为 [英] Interesting event "Dispose" behaviour

查看:93
本文介绍了有趣的事件"配置"行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我们的.NET WinForms应用程序发现有趣的现象。我们有很多有MDI子添加MDI窗体。这些子窗体听广播事件,在本质上是调用刷新itsself。本次活动是在基类和子窗体添加监听事件的声明。

I have noticed interesting behaviour in our .NET WinForms app. We have an mdi form that has many mdi children added. These child forms listen to a "broadcast" event which is in essence a call to refresh itsself. The event is declared in a base class and the listening events added in the child forms.

我注意到,即使这些子窗体被关闭,事件仍在被击中,如果未明确地在Dispose()方法去除该事件。

I've noticed that even when these child forms are closed, the events are still being hit, if the event is not explicitly removed in the Dispose() method.

这背后的理由?当然,如果关闭窗体时,事件应该被分离/处理?是不是因为实际的事件本身在外部类被声明?这就是我假设。

What is the reasoning behind this? Surely if the form is closed, the events should be detached/disposed of? Is it because the actual event itself is declared in an outside class? This is what I am presuming.

有识之士将不胜感激。

(使用C#,.NET 3.5)

(using C#, .NET 3.5)

推荐答案

本次活动,仍处于范围,因为它是主窗体上,还是要在子窗口委托的引用。因此,关闭窗口将不会出售的对象,因为它也仍然是通过范围本参考。这是一种很常见的方式获得在.NET中内存泄漏。同时认为,因为孩子窗口仍然在范围内的一切窗口内仍是在范围上,也不会得到收集。

The event, which is still in scope since it is on the main form, still has a reference to the delegate in the child window. Therefore closing the window will not dispose of the object because it too is still in scope through this reference. This is a very common way the get a "memory leak" in .NET. Also consider that because the child window is still in scope everything inside the window is still in scope and also won't get collected.

至于为什么该窗口没有拆离关闭所有事件处理程序。这将是,如果它做的非常奇怪的现象。仅仅因为你已经关闭的窗口并不意味着你完成它,你可以重新打开它,从中将数据保存到持久化状态。调用close在窗口上有超过调用任何其他方法,它不处理窗口,将其标记为收藏或任何其他没有特殊的属性。

As for why the window doesn't detach all event handlers on close. It would be very strange behaviour if it did. Just because you have closed a window doesn't mean you are finished with it, you could reopen it, save data from it to persist state. Calling close on a window has no special properties over calling any other method, it doesn't dispose of the window, mark it for collection or anything else.

这篇关于有趣的事件"配置"行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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