Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AddHandler/RemoveHandler Not Disposing Correctly

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#?

like image 912
MagicKat Avatar asked Dec 17 '22 10:12

MagicKat


2 Answers

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.

like image 113
Gishu Avatar answered Jan 20 '23 13:01

Gishu


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.

like image 37
albertein Avatar answered Jan 20 '23 13:01

albertein