AddHandler / RemoveHandler处理不正确 [英] AddHandler/RemoveHandler Not Disposing Correctly
问题描述
使用 AddHandler
方法,如果我从不使用 RemoveHandler
,在某些情况下会导致内存泄漏,并且情况?我不太确定这是真的。
Using the AddHandler
method, if I never use RemoveHandler
, will that lead to memory leaks in some conditions and situations? I'm not so sure about the truth of this.
还有其他导致内存泄漏的原因,而这些原因仅在VB中才有,而不是C#?
And are there other causes to memory leaks that are solely available in VB as opposed to C#?
推荐答案
通常不会。但是可能存在。
订阅事件,您基本上可以将方法的委托(如果有的话,可以使用func指针)提供给事件发布者,只要您不使用-=运算符取消订阅,该事件发布者就会保留该事件。
Well usually it doesn't.. but the possibility exists.
When you subscribe to an event, you basically give a delegate (a func pointer if you will) to your method to the event publisher, who holds on to it as long as you do not unsubscribe with the -= operator.
例如,生成一个子窗体,该窗体订阅了窗体上的Click按钮事件。
So take for example, the case where you spawn a child form and the form subscribes to the Click button event on the form.
button1.Click += new EventHandler(Form_Click_Handler);
现在,按钮对象将保留在窗体引用上。当窗体关闭/处置/设置为null不再需要form和button;内存被回收。
Now the button object will hold on to the form reference.. When the form is closed/disposed/set to null both form and button are not needed anymore; memory is reclaimed.
当您拥有寿命更长的全局结构或对象时,就会发生麻烦。可以说Application对象维护着一个打开的子窗口的列表。因此,无论何时创建子窗体,应用程序对象都会订阅Form事件,以便可以在其上保留选项卡。在这种情况下,即使关闭/放置了表单,应用程序对象也会保持活动状态(非垃圾对象会保留对表单的引用),并且不允许回收其内存。当您继续创建和关闭窗口时,您的应用会占用越来越多的内存,从而导致泄漏。因此,您需要明确地取消订阅,以从应用程序中删除表单引用。
The trouble happens when you have a global structure or object which has a bigger lifetime. Lets say the Application object maintains a list of open child windows. So whenever a child form is created, the application object subscribes to a Form event so that it can keep tabs on it. In this case, even when the form is closed/disposed the application object keeps it alive (a non-garbage object holds a ref to the form) and doesn't allow its memory to be reclaimed. As you keep creating and closing windows, you have a leak with your app hogging more and more memory. Hence you need to explicitly unsubscribe to remove the form reference from the application.
childForm.Event -= new EventHandler(Form_Handler)
因此,建议您使用一个取消订阅块(-=)来补充您的订阅例程(+ =)...但是在股票情况下,您可以不用它。
这篇关于AddHandler / RemoveHandler处理不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!