How to resolve the winforms error “A generic error occurred in GDI+. ”?

梦想的初衷 提交于 2019-12-07 08:44:13

问题


I am facing the following exception in my C#.net win forms application.

A generic error occurred in GDI+.
at System.Drawing.Graphics.CheckErrorStatus(Int32 status)
at System.Drawing.Graphics.DrawRectangle(Pen pen, Int32 x, Int32 y, Int32 width, Int32 height)
at WeifenLuo.WinFormsUI.Docking.DockWindow.OnPaint(PaintEventArgs e)
at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)
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.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)

The most confusing point is that, it occurs very rarely when the application loading a form (which contains some rich graphics, WPF work etc.), could say about 90% of the time the form is loaded successfully. but very few times it happens to be reproduced and also only on some machines, at some other machines this form is works 100% of the time and never face this exception.

I am not getting any idea why this exceptions happening, because it also not showing the exact stack trace which causes the exception. Please suggest if one have any idea about how to deal with it.


回答1:


Your code is probably leaking GDI resources badly. Have a look with Taskmgr.exe, Processes tab. View + Select Columns and tick Handles, USER objects and GDI objects. Run your program and observe the displayed values for your process. A constantly climbing value for GDI objects spells trouble, the show is over when it reaches 10,000.

Exactly what might cause the leak is not quite that easy to diagnose. Although you can single-step your code in the debugger and keep an eye on the taskmgr number. The classic mistake is creating pens and brushes in a Paint event handler and not disposing them. Without the garbage collector running often enough to clean up. Use the using statement to fix.



来源:https://stackoverflow.com/questions/9362184/how-to-resolve-the-winforms-error-a-generic-error-occurred-in-gdi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!