Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

.net - How to debug GDI Object Leaks?

I'm not quite sure how to go about doing this. It is a large app, and we are having GDI object "leaks" on most of our forms.

Is there a tool to help out? Is there a tutorial on how to use such a tool?

Should I just start deleting code from our forms until I narrow the offender down? (there is ALOT of code).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is pretty rare to exceed the 10,000 object limit for GDI objects only, the garbage collector will take care of them when you don't call their Dispose() method yourself. A much more likely failure mode is exceeding the object limit for windows. Which is very easy to do in Winforms, Controls.Clear() or Controls.Remove() will get you there in a hurry when you don't explicitly dispose the removed controls. The garbage collector can't clean them up.

You can get a good diagnostic from Taskmgr.exe, Processes tab. View + Select Columns and tick Handles, USER Objects and GDI Objects. Observe these numbers for your process while you use it. A steadily climbing number of one of them is a sure sign you'll get Windows to bomb your program when it refuses to give you any more. The default quota is 10000 for each. USER Objects is the one that indicates you have a problem with Controls.Clear/Remove, GDI Objects is the one that indicates that you are leaking System.Drawing objects. Perfmon.exe is a good tool to see if the garbage collector is running often enough to get non-disposed System.Drawing objects released.

With the common wisdom that calling Dispose() explicitly where required is a good practice. Especially for Image and Bitmap objects, they take very little GC memory but lots of unmanaged memory, pretty easy to bomb a program with OOM when you don't dispose them. Beware the nasty trap in Properties.Resources, you get a new object every single time you use it and it needs to be disposed. Always use the using statement in painting code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...