Posts

Showing posts with the label leak

.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...

.NET: Leak en Windows Forms

Versión en inglés / English version Consideremos este código dentro de un Form: 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(); } Tal vez haya que cambiar 150 y 200 por algo más grande en tu sistema, pero eventualmente esto explotará diciendo algo del estilo "Cannot create window handle". Esto es porque el Clear() no libera instantáneamente los botones; el GC debería hacerlo eventualmente, pero parece que no llega a tiempo. ¿A qué se debe esto? En primer lugar, debemos considerar que Windows Forms está montado sobre la API de Win32, así que detrás de esto hay un bucle donde se procesan mensajes (message pump). En segundo lugar, debemos considerar que en Win32, una ventana sólo puede ser destruida por el mismo thread que la creó. Por lo tanto, el Garbage Collector, al destruir los controles, debe despachar...