Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

GDI+ handles & exceptions

Calling GetHicon() in the following snippet causing a generic exception in GDI+ after a few thousand iterations.  Any of you Microsoft guys know how to release those handles so GDI+ doesn't run out?

while ( true )
{
  Bitmap bm = new Bitmap(16,16);
  IntPtr bmh = bm.GetHicon();
  bm.Dispose();
  Application.DoEvents();
}

My current workaround involves restarting the application-- not an optimal solution. :)

Also, is there a plan/schedule for improved exception reporting in GDI+?  The generic GDI+ exception seems to come up often in System.Graphics methods.

John Lemberger
Friday, May 23, 2003

I had a little dig using Reflector ( http://www.aisto.com/roeder/dotnet/ ) and found System.Drawing.SafeNativeMethods.IntDestroyIcon which looks promising. It's internal - but you can cheat with a little Reflection:

MethodInfo _destroyIconMethod = null;

void destroyIcon(object o, IntPtr p)
{
  if(_destroyIconMethod==null)
  {
      Type safeNativeMethodsType = null;
      foreach(Type t in typeof(Bitmap).Assembly.GetTypes())
      {
        if(t.Name == "SafeNativeMethods")
        {
            safeNativeMethodsType = t;
            break;
        }
      }
      _destroyIconMethod = safeNativeMethodsType.GetMethod("IntDestroyIcon", BindingFlags.NonPublic | BindingFlags.Static);
  }
  _destroyIconMethod.Invoke(null, new object[]{new HandleRef(o,p)});
}

//...

while ( true )
{
  Bitmap bm = new Bitmap(16,16);
  IntPtr bmh = bm.GetHicon();
  destroyIcon(bm,bmh);
  bm.Dispose();
  Application.DoEvents();
}

Duncan Smart
Friday, May 23, 2003

*  Recent Topics

*  Fog Creek Home