简体   繁体   中英

Do I need to call Graphics.Dispose()?

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?

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.

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.

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

using(var g = Graphics.FromImage()) {
    // use the resource 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM