Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I remove an event handler?

I have a list of Button, and I add an event handler for each button:

List<Button> buttons = new List<Button>();

for (int i = 0; i < 10; i++)
{
   Button btn = new Button();
   btn.Click = new RoutedEventHandler(OnbtnClick);
   buttons.Add(btn);
}

Then I clear the list:

/* Have I to remove all events here (before cleaning the list), or not?
foreach (Button btn in buttons)
   btn.Click -= new RoutedEventHandler(OnbtnClick);
*/

buttons.Clear();
like image 860
Nick Avatar asked Jun 13 '12 18:06

Nick


1 Answers

When you clear the list you clear all references to the handlers along with them. Once your handlers leave scope (which is to say when the function finally exits and no objects have references to the created handlers), the Garbage Collector will get around to removing all related memory (on its own schedule of course).

So no, you don't need to manually delete the handlers.

like image 100
Joel Etherton Avatar answered Sep 21 '22 06:09

Joel Etherton