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()
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With