0
Answer

Anonymous event handlers and garbage collection

Kevin Coulombe

Kevin Coulombe

16y
4.7k
1
I tried to formulate the situation as clearly as I could, but that's still a lot of technical terms to assimilate in very few sentences. Sorry about that, I'll clarify if you have any questions.

Some background.
When you add to the FormClosing event of a Form, an event handler representing a method from your custom control, the FormClosing event keeps a reference to the custom control. This means that even if you dispose of the custom control and delete all references to it, it will not be garbage collected unless you remove the event handler from the FormClosing event (and, unfortunately there are no Clear method on events).

My situation.
I have a context menu containing menu items that the user can check to add some items to selections. The list of selections is dynamic and can be changed at will, so the menu items are dynamically generated and added to the context menu. Then I bind an anonymous event handler to the CheckStateChanged that uses the Id variable from the selection's DataRow. Internally, the compiler will create a temporary anonymous class to hold the variables from the event handler's declaration scope so I may use the DataRow's members. The anonymous event handler will become an anonymous method inside the generated anonymous class and when I dispose of my menu items to refresh the list of selections, they will be garbage collected correctly.

The question.
Am I right or did I miss something that might lead to a memory leak in my desing?