Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How deep does Controls.Clear() clean up?

I'm using a TableLayoutPanel which is dynamically filled with other TablelayoutPanels.

Now I'm wondering what happens when I call TableLayoutPanel.Controls.Clear on the dynamically filled TableLayoutPanel. Obviously, all the sub-layouts are removed, but how about their children? Are they properly disposed as well or do I need to fear a memory leak?

Should I recursively remove the children of the children before calling Clear()?

like image 681
Xaser Avatar asked Mar 23 '13 11:03

Xaser


1 Answers

Clear doesn't dispose the controls, leading to a memory leak. From the link:

Calling the Clear method does not remove control handles from memory. You must explicitly call the Dispose method to avoid memory leaks.

Since disposing within a loop messes up the indexing, you can either copy the control collection to another list and perform a ForEach loop on them or use a backwards For loop.

 for (int i = myTableLayoutPanelControls.Count - 1; i >= 0; --i) 
    myTableLayoutPanelControls[i].Dispose();
  

Calling Dispose will remove the controls from memory (when the GC picks it up). This will also handle the calling of the child control's Dispose method.

One catch is if you've got a custom control that implements IDisposable or you're overriding the Dispose method without calling the base method. In your object's Dispose method you need to ensure that you've unsubscribed from any events outside your scope. If you don't, that reference will keep your object alive.

like image 188
keyboardP Avatar answered Sep 30 '22 11:09

keyboardP