I am getting the below error and call stack at the same time everyday after several hours of application use. Can anyone shed some light on what is happening?

System.InvalidOperationException: BufferedGraphicsContext cannot be disposed of because a buffer operation is currently in progress.

at System.Drawing.BufferedGraphicsContext.Dispose(Boolean disposing)

at System.Drawing.BufferedGraphicsContext.Dispose()

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.ScrollableControl.WndProc(Message& m)

at System.Windows.Forms.ToolStrip.WndProc(Message& m)

at System.Windows.Forms.MenuStrip.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)


a shot in the dark - are you painting from multiple threads? If you are doing painting related work, do it on the GUI thread or synchronize your code carefully.

I don't believe that I am...
+2  A: 

There is a very long MSDN forums discussion of this error here. In most cases the error is apparently associated with either:

  1. An underlying OutOfMemory problem, which manifests as the BufferedGraphicsContext exception, possibly due to a framework bug.
  2. A GDI object leak (creating GDI objects and not disposing them).

I recall seeing this error myself a year or so ago, and it was definitely associated with a memory problem that made our app fill up all available VM after a long run, so #1 agrees with what I have observed.

Thanks for the post...this sounds like the cause of the problem.