C# – Why are Font Handles not being disposed

.netc++winforms

I am using GDIView to try to track down the source of a few lingering GDI handles, and the source seems to be Fonts used in a menu on the form. The only way I've found to make sure the font handles are GCed is to explicitly set them to null like this:

tsmiTextLocation.Font = null;
tsmiLocationSelection.Font = null;

This doesn't seem quite right to me, but I'm not sure how else to address the issue. Has anyone else run into this problem before?

Best Solution

Even though it is best practice to call IDisposable.Dispose() yourself either by calling it directly or leveraging the using keyword. Some GDI+ objects are exception to this rule.

GDI+ contains predefined brushes and pens in Brushes and Pens classes. You should not call Dispose() on objects returned by members of these classes (or other GDI pre-cached objects which you haven't created by new on your own).

And a note from MSDN - Font.Dispose:

Always call Dispose before you release your last reference to the Font. Otherwise, the resources it is using will not be freed until the garbage collector calls the Font object's Finalize method.