views:

1698

answers:

2

I have heard that calling AddHandler, but not calling RemoveHandler doesn't remove the handle to the event under certain conditions, leaving the control/object as active and not diposed, and thus leading to memory leaks. Is there any truth to this? Are there other causes to memory leaks that are solely available in VB as opposed to C#?

A: 

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.

AlbertEin
+7  A: 

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.

Gishu