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.

2 Comments

Comments have been disabled for this content.