Leak Found in .NET ContextMenu

My colleague Doug Ware of Magenic found another leak in the .NET framework this week.  It seems that every time a MenuItem is added to a ContextMenu in .NET WinForms, it adds a reference to the MenuItem in an internal static hashtable.  This may not be “wrong” if you only setup your context menu one time, but if you do things dynamically it means that all the old context menuitems are still technically reachable.  To make things worse, the menuitems contain a reference to their parent, which is often a form, which might have references to large objects like datasets or images.  Of course, once you find the problem and know what to look for, you can always find other mentions of it already on the net, along with the work-arounds.  Its again frustrating though that something that's potentially so common, with a big impact too, which has been reported to Microsoft for quite some time apparently, is still not noted in any official Microsoft list that I can find.  So if you are using ContextMenus -- beware -- and get the .NET Memory Profiler to help you find your own similar leaks.  By the way, Doug is really getting good at this -- I found a leak in our own code today that I probably wouldn't have found before helping him recently -- although he still found the solution before I could.
Published Friday, February 20, 2004 10:05 PM by PaulWilson

Comments

# Leak in .NET ContextMenu

Leak in .NET ContextMenu

Saturday, February 21, 2004 2:47 PM by TrackBack

# re: Leak Found in .NET ContextMenu

Hiya,
Just as an aside, this problem occurs also on MainMenus - not just ContextMenus.

Sunday, February 22, 2004 10:30 PM by Zubin Appoo

# re: Leak Found in .NET ContextMenu

Thanks for that info Zubin. Very little, if any, of our main menu is dynamic, so hopefully that's why we haven't noticed this one yet.

Sunday, February 22, 2004 10:38 PM by Paul Wilson

# Leak in .NET ContextMenu

Tuesday, January 04, 2005 4:45 AM by TrackBack

Leave a Comment

(required) 
(required) 
(optional)
(required)