Share via


Rule of thumb for System.Drawing

A friend of mine ran into this the other day.

If you call a method to get a handle some sort of System.Drawing object, you may be creating an object that needs to be cleaned up through P/Invoke or some other function call.

Bitmap.GetHIcon - requires p/invoking DestroyIcon.
Font.ToHFont - requires p/invoking DeleteObject
Graphics.GetHdc - requires calling Graphics.ReleaseHdc

The MSDN2 documentation seems to be a lot more clear about this, so if you're accessing a handle, you might want to pop over there to see if there are cleanup instructions. You might also consider using the GDICounter and reading the background info on when to use Dispose.

Comments

  • Anonymous
    July 25, 2006
    Isn't this the problem that SafeHandle was invented to solve?
  • Anonymous
    July 25, 2006
    If that's the way you want to wrap up your cleanup logic, that's fine.  You still have to write the call to the appropriate cleanup function for the handle.

    It's better to explicitly delete the object than clean it up in finalization.
  • Anonymous
    July 29, 2006
    I've been bitten by this.  It seems foolish to expose these through the BCL only to require PInvokes to clean them up after their use; if you can create them with the built-in .NET functions, why can't they be destroyed likewise?
  • Anonymous
    July 30, 2006
    The comment has been removed