Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can see what's going on by using TaskMgr.exe, Processes tab. View + Select Columns and tick "USER objects". This columns tracks window handles. Note that this column's value keeps increasing as you click the button. Calling GC.Collect() doesn't make it go down. Your program will crash and burn once it reaches 10,000.</p> <p>The Control class is the only class in the .NET framework I know that <em>requires</em> calling Dispose(). The finalizer is not enough to ensure that the window handle is released. Calling Dispose() is normally completely automatic, the parent of a control does it when it gets disposed. The ultimate parent is the Form object, it automatically disposes itself (and its child controls) when it is closed.</p> <p>But this doesn't happen when you remove controls from the Controls collection yourself. You cannot use the Clear() method, you have to do it like this:</p> <pre><code> while (panel.Controls.Count &gt; 0) panel.Controls[0].Dispose(); </code></pre> <p>The reason it works this way is that the lifetime of a window is managed by Windows, not your program. As long as the window is alive, the control wrapper should not be garbage collected. Windows Forms keeps track of window handles in an internal table. As long as Handle is valid, the table ensures that the Control class wrapper can't be garbage collected. In other words, there is always at least one reference to the Control object.</p> <p>That reference is not removed from that internal table until the window gets the WM_NCDESTROY message, the last message a window procedure receives before the window handle is destroyed. Removing the control from a Controls collection is not enough to destroy the window. If you don't explicitly call Dispose(), it will turn into a "zombie", an invisible window whose Control wrapper reference you can't obtain.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload