How to debug GDI Object Leaks?

It is pretty rare to exceed the 10,000 object limit for GDI objects only, the garbage collector will take care of them when you don’t call their Dispose() method yourself. A much more likely failure mode is exceeding the object limit for windows. Which is very easy to do in Winforms, Controls.Clear() or Controls.Remove() will get you there in a hurry when you don’t explicitly dispose the removed controls. The garbage collector can’t clean them up.

You can get a good diagnostic from Taskmgr.exe, Processes tab. View + Select Columns and tick Handles, USER Objects and GDI Objects. Observe these numbers for your process while you use it. A steadily climbing number of one of them is a sure sign you’ll get Windows to bomb your program when it refuses to give you any more. The default quota is 10000 for each. USER Objects is the one that indicates you have a problem with Controls.Clear/Remove, GDI Objects is the one that indicates that you are leaking System.Drawing objects. Perfmon.exe is a good tool to see if the garbage collector is running often enough to get non-disposed System.Drawing objects released.

With the common wisdom that calling Dispose() explicitly where required is a good practice. Especially for Image and Bitmap objects, they take very little GC memory but lots of unmanaged memory, pretty easy to bomb a program with OOM when you don’t dispose them. Beware the nasty trap in Properties.Resources, you get a new object every single time you use it and it needs to be disposed. Always use the using statement in painting code.

Leave a Comment