The Controls collection performs two important tasks. First, it tracks the child controls of the container. The order of the management objects in the collection determines their Z-order. Secondly, he ensures that controls are removed when their parent is destroyed. For this reason, you do not need to manage the controls yourself, as you often have to do with other .NET classes that implement IDisposable.
Which leads to an unpleasant error in your code, the Controls.Clear () method simply removes the controls from the collection, but does not delete them. This is a very bad leak that will make your program bold and slow, which will ultimately crash when Windows refuses to provide it with more window handles. You will need to write this as follows:
while (this.pnlContent.Controls.Count > 0) this.pnlContent.Controls[0].Dispose();
Which now also makes it obvious why the control counter decreases when you call the Close () method, which provides a form object that automatically removes it from its Control Control collection.
Disposing a control simply destroys the native resources of the Windows operating system used by the control. The Handle property is the most obvious. Otherwise, the .NET object will not disappear, which requires the garbage collector to run. Saving a link to a custom control is a bad idea, the GC will not destroy it as long as there is a link to it, and you tend to get an ObjectDisposedException when trying to use it.
source share