.NET: Leak in Windows Forms
Spanish version / Versión en Español Consider this Windows Forms code: int i, j; for (i = 0; i < 150; i++) { for (j = 0; j < 200; j++) { this.Controls.Add(new Button()); } this.Text = String.Format("i={0}", i); this.Controls.Clear(); } You might need to change 150 and 200 to larger values for your system, but this code should eventually crash saying something like "Cannot create window handle". This is because the Clear() call does not instanltly release the Buttons. The GC should eventually do it, but he fails to do it on time. What's the cause for this? First of all, consider that Windows Forms is built on top of the Win32 API, so there is a message pump behind. Second, consider that in Win32, a window handle or any other graphic resource can only be destroyed by the thread who created it. Therefore, when the GC wants to destroy a Button, he must dispatch the call to the GUI thread. And he does it via the messag...