Should I remove the event handler?

I have a Button list, 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(); 
+6
source share
2 answers

When you clear the list, you delete all references to the handlers along with them. After your handlers leave the scope (that is, when the function finally exits and no objects refer to the created handlers), the garbage collector will manage to delete all the associated memory (according to its own schedule, of course).

No, you do not need to manually remove handlers.

+5
source

check this solution: How to remove all event handlers from a control

this is what is after him. Direct this help.

+1
source

Source: https://habr.com/ru/post/918013/


All Articles