tags:

views:

243

answers:

3

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?

+1  A: 

Setting to null will make them be garbage collected eventually, and the finalizer will be called. This could take some time, if there is no memory pressure the objects may live for a while.

System.Drawing.Font implements IDisposable, so you should call Font.Dispose to free up any unmanaged resources (the GDI handles) deterministically.

I believe you have to call Dispose explicitly, since the font may be shared and therefore the form can't dispose of the font in its Dispose method.

Michael
But dispose for the font should be called by the dispose method of the form, right? I'm not seeing this with any of the other controls on the form, most of which have associated font objects.
Shane Fulmer
Ah, I did not know that you were disposing of the form.I'd expect the form;s dispose should free all unmanaged resources. You could try putting a breakpoint on Font.Dispose in the debugger and verify that it is called when Dispose on your form occurrs.
Michael
Did a little quick research and updated the answer.
Michael
I guess my question is why this would only be an issue on these controls. I don't have to do this anywhere else on the form, where fonts could be shared as well.
Shane Fulmer
A: 

A best practice is that if the class implements IDisposable, you should make every attempt to call Dispose on your instances.

Most GDI classes support IDisposable.

MedicineMan
+4  A: 

Even it is best practise to call IDisposable.Dispose() by yourself or in using block 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.

Jozef Izso
Is there any way to know what the last reference is within a form? Or should I be disposing of all fonts recursively in the dispose method of my forms?
Shane Fulmer