Event handler and memory leak

I am analyzing a VB.NET project and some objects (child MDIs ) that are located but not deleted using GC .

The MemoryProfiler analysis finds, among other things, the following:

"This instance is located and remains indirectly associated with EventHandler. This often indicates that EventHandler was not properly and is a common cause of memory leak. The following are examples directly related to EventHandler (s). Study them to get more information about this problem ... "

Now I'm trying to understand what this means and how to fix it.

I have an MDI form and a child form. The detailed form is not collected by the GC after opening / closing, apparently because it remains stationary (indirectly?) Referenced by MDIForm EventHandlerList ...

What could it be and how to fix it?

I tried the fix recommended in this thread , because I had a problem with the MDI link in the PropertyStore , now it is fixed, but the MDI EventHandlerList link to the child form appeared ...

After some code analysis, I noticed some

 AddHandler newMenu.Click, AddressOf ClickMenu 

without the previous RemoveHandler newMenu.Click, AddressOf ClickMenu . Could this be the main reason?

And, the suggestion is Handles

 Private Sub ClickMenu(sender as Object, e as EventArgs) Handles newMenu.Click 

better than

 RemoveHandler newMenu.Click, AddressOf ClickMenu AddHandler newMenu.Click, AddressOf ClickMenu 

from the memory allocation point?

+5
event-handling memory-leaks
source share
2 answers

EventHandlerList used by classes that provide a large number of events for more efficient memory management, only allocating space for the event support field when necessary, and not when an event is declared. Thus, all events for the main form are saved.

I would expect the child form to track when its parent can close (this is a common use case), and it did not unsubscribe from the FormClosing or FormClosed event when it received this event. However, this is just a hunch. To confirm, look at the implementation of the child form and find all cases when it subscribes to events from the parent form, and then make sure that there is a corresponding unsubscribe from these events.

Update
A selected menu handler that has not been deleted may very well be the root of the problem you are seeing. Try adding a remove call and see if this fixes the leak.

+4
source share

There is another object that refers to an object that must be deleted by the GC through an event handler. Meaning: There is another object that is still subscribing to the event of the located object.

You can solve this problem by unsubscribing from the event (remove event handlers from the event) if you want to delete this object.

+2
source share

All Articles