我是否需要调用Graphics.Dispose()?Graphics、Dispose

2023-09-03 05:11:12 作者:时间消磨人心

在一个VB.NET程序我创建一个新的位图图像,然后我打电话Graphics.FromImage得到一个图形对象上绘制位图。该图像然后被显示给用户。

In a VB.NET program I'm creating a new bitmap image, I then call Graphics.FromImage to get a Graphics object to draw on the bitmap. The image is then displayed to the user.

所有我一直看到了code样品调用.Dispose()的位图和图形对象,但没有任何需要做的是,当既没有触及磁盘上的文件?是否有不会被垃圾收集器清除了所有其他非托管资源,这些对象有可能抢下?

All the code samples I've seen always call .Dispose() on Bitmaps and Graphics objects, but is there any need to do that when neither have touched files on disk? Are there any other unmanaged resources that these objects might have grabbed that wouldn't be cleared by the garbage collector?

推荐答案

是的。

总是调用的Dispose()上的任何对象,它实现的IDisposable 。 GDI处理用的图形对象非托管,并要求当您完成与他们处理。

Always call Dispose() on any object that implements IDisposable. GDI handles used by graphics objects are unmanaged and require disposing when you are finished with them.

最佳做法是包装在一个使用块。已经有关于这一主题的几个SO问题,顺便说一句。

Best practice is to wrap in a using block. There have been several SO questions on this topic, BTW.