I'm populating a ToolStripMenu
with entries from an XML
file. Each ToolStripItem
added to the menu automatically gets about a dozen event handlers assigned to it. The user has the option to change the XML
and refresh the menu, which clears everything using:
menuStrip1.Items.Clear();
This repopulates from the XML
and refreshes the Form. It appears that the event handlers for all these dynamic items are never removed from memory. Most of the items don't sit directly on menuStrip1 but in dynamically created submenus which reside on menuStrip1
.
Nevertheless, I can sit there refreshing the Form and the memory just balloons out of control, adding 5-10 MB
per refresh of about 100 dynamic ToolStripItems.
It can quickly reach hundreds of MB which crashes the application.
The ToolStripItems
also load other things such as properties and icons, but it seems to be the event handlers which use most of the added memory. I commented out all the handlers and the memory became far more (but not completely) sustainable with each refresh.
Is it necessary to enumerate through all the menus and submenus and individually release each event handler to assure it's not sticking around?
If you dispose/delete both the event handler and the object it's subscribing to, you should be OK. Otherwise, yeah, you will have to unsubscribe each handler.
Or look at a different way of subscribing--not compiler-generated events. See http://paulstovell.com/blog/weakevents for an example)