Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

.net - Event handler and memory leaks

I analyze a VB.NET project and there are some objects (child MDI form) that are disposed, but not removed by the GC.

The MemoryProfiler analysis find, among others, the following:

"This instance is disposed and still indirectly rooted by an EventHandler. This often indicates that the EventHandler has not been properly removed and is a common cause of memory leaks. The instances below are directly rooted by EventHandler(s). Investigate them to get more information about this issue..."

Now, I try to figure out what should this mean and how to fix it.

I have a MDI form and a child form. The child form is not collected by the GC after a open/close, apparently because remains still (indirectly?) referenced by the MDIForm EventHandlerList...

What can it be and how do I to fix it?

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

After some code analysis I observed some

AddHandler newMenu.Click, AddressOf ClickMenu

without preceding with RemoveHandler newMenu.Click, AddressOf ClickMenu. Could it be the main cause?

And, a propos, is the Handles

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

better that

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

from the memory allocation point of view?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The EventHandlerList is used by classes that provide large numbers of events to more efficiently handle memory by only allocating space for the event backing field when it is needed rather than when the event is declared. All events for the main form are therefore stored there.

I would expect the child form was monitoring when its parent may close (this is a common use-case) and it didn't unsubscribe from the FormClosing or FormClosed event when it received that event. However, that's just a guess. To confirm, look at your child form implementation and find all cases where it subscribes to events from the parent form, then make sure there is a corresponding unsubscription from those events.

Update
The menu handler you found that was not removed could well be the root of the issue you see. Try adding the remove call and see if that addresses the leak.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...