I'm not quite sure how to go about doing this. It is a large app, and we are having GDI object "leaks" on most of our forms.
Is there a tool to help out? Is there a tutorial on how to use such a tool?
Should I just start deleting code from our forms until I narrow the offender down? (there is ALOT of code).
A good solution for detecting GDI leaks is to use dedicated tools such as the Purify or BoundsChecker tools I mentioned earlier.
The Graphics Device Interface (GDI) is a legacy component of Microsoft Windows responsible for representing graphical objects and transmitting them to output devices such as monitors and printers.
GDIView is a unique tool that displays the list of GDI handles (brushes, pens, fonts, bitmaps, and others) opened by every process. It displays the total count for each type of GDI handle, as well as detailed information about each handle.
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.
Get a copy of Red Gate’s Memory Profiler. http://www.red-gate.com/products/dotnet-development/ants-memory-profiler/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With