Do I need to call Graphics.Dispose()?

ぃ、小莉子 提交于 2019-12-01 17:20:39

Yes.

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.

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

Wrap it in a using statement for the scope in which you need it. Then don't worry about explicitly calling Dispose()

Pseudocode:

using(new Graphics() = Graphics.FromImage)
{
     //Magic happens...
}

Yes, you should call Dispose. It is not related to touching the disk; it is related to using unmanaged resources that need to be released properly back to the operating system. In the case of the Graphics object, I would assume that it allocates device context handles that should be released when they are not needed anymore.

The rule with Dispose() is that if you created an object that is IDisposable, then you are supposed to call it. The best way is within a using block or a finally.

It might be that you didn't need to do it, but Dispose() will decide that.

If you got an object, but didn't call the constructor, then you need to check the documentation for the method that returned it to see if it expects you to call Dispose() or it will.

Graphics implements IDisposable, so you should call Dispose to ensure clean up of unmanaged resources.

Unmanaged resources are not handled by the garbage collector, so they must be handled manually. This is typically done by the Dispose() method in order to provide cleanup at a well defined point in time. It may also be handled by a finalizer but in that case the resource(s) will be in use longer than necessary.

The easiest way to ensure that Dispose is called in all cases is to employ the using construct. E.g.

using(var g = Graphics.FromImage()) {
    // use the resource 
} 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!