Reputation: 4305
I Load a User Control inside a panel, the user Control itself contains so many inner controls such as tab pages, panels, buttons and also inside its panels there will be some other user controls.
Let say I Load the Main User Control inside the MainPanel, If I use this:
MainPanel.Controls.Clear();
It will not clear the memory, so I use this instead:
while (MainPanel.Controls.Count > 0) MainPanel.Controls[0].Dispose();
But it seems it will Dispose the Main User Control and will clear memory just a little and I think all controls inside this user control still exist in the memory. How can I iterate recursively through all of the inner controls and dispose them one by one?
Furthermore, inside the user control, there are several grid controls that load some data. They are not binding to any database, just fetching some data by LINQ from the database and new
command.
Do I need to destroy those data before disposing the control or they will be deleted from memory by control disposing?
Upvotes: 0
Views: 1281
Reputation: 26450
https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/unmanaged?view=netframework-4.8
Call Dispose when you are finished using the Component. The Dispose method leaves the Component in an unusable state. After calling Dispose, you must release all references to the Component so the garbage collector can reclaim the memory that the Component was occupying. For more information, see Cleaning Up Unmanaged Resources and Implementing a Dispose Method.
for (int i = MainPanel.Controls.Count - 1; i >= 0; i--) {
MainPanel.Controls[i].Dispose();
}
You don't need to dereference any other data. Only the controls so that they can be picked up by gc.
Bear in mind that if you dereference ControlA which has ObjectB, then ObjectB is also dereferenced and can be picked up.
Upvotes: 2