AddHandler/RemoveHandler Not Disposing Correctly

泪湿孤枕 提交于 2019-12-18 08:57:38

问题


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.

And are there other causes to memory leaks that are solely available in VB as opposed to C#?


回答1:


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.

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);

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.

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)

So its recommended that you have a unsubscribe block (-=) complementing your subscribe routine (+=)... however you could manage without it for the stock scenarios.




回答2:


If object a is suscribed to the object b event then object b will not be collected until object a is collected.

An event suscription counts as a reference to the publisher object.

And yes, this happens on C# too, i has nothing to do with the language.



来源:https://stackoverflow.com/questions/151303/addhandler-removehandler-not-disposing-correctly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!