Do I need to call Graphics.Dispose()?

2020-04-07 06:02发布

问题:

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.

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?

回答1:

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.



回答2:

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...
}


回答3:

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.



回答4:

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.



回答5:

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 
} 


标签: .net dispose