Search code examples
c#windowshandlesystem.drawing

WinForms too many handles


I our production, my application caused two different exceptions:

System.ArgumentException: Invalid Parameter.
   at System.Drawing.Image.get_RawFormat()
   at System.Windows.Forms.ToolStripItem.set_Image(Image value)
   at Zeiss.IMT.IME.CmmUI.Tools.ToolControl.updateControls()

There is another exception that i suppose to have the same cause:

System.ComponentModel.Win32Exception: The operation completed successfully
   at System.Drawing.BufferedGraphicsContext.CreateCompatibleDIB(IntPtr hdc, IntPtr hpal, Int32 ulWidth, Int32 ulHeight, IntPtr& ppvBits)
   at System.Drawing.BufferedGraphicsContext.CreateBuffer(IntPtr src, Int32 offsetX, Int32 offsetY, Int32 width, Int32 height)
   at System.Drawing.BufferedGraphicsContext.AllocBuffer(Graphics targetGraphics, IntPtr targetDC, Rectangle targetRectangle)
   at System.Drawing.BufferedGraphicsContext.AllocBufferInTempManager(Graphics targetGraphics, IntPtr targetDC, Rectangle targetRectangle)
   at System.Drawing.BufferedGraphicsContext.Allocate(IntPtr targetDC, Rectangle targetRectangle)
   at System.Windows.Forms.Control.WmPaint(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.DataGridView.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

At both exceptions, the windows task manager shows up a lot of handles (>8500). So the windows handle limit is reached and the application fails to allocate more memory/handles.
So far i understand the problem.
In this case i'm heavily using GDI drawing via System.Drawing. So i searched my code where graphics handles are not released - without success.

So the question is:
How can i find unreleased (native) handles???


Solution

  • You could use memory profile tools. For example this one: http://www.red-gate.com/products/dotnet-development/ants-memory-profiler/

    But are you disposing all Disposable objects? Brushes and so on..

    You could post your drawing code perhaps we can see something wrong.

    Perhaps there are some brushes,... that aren't disposed.