tags:

views:

330

answers:

5

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  A: 

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.

Fredrik Mörk
+3  A: 

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...
}
Chris Ballance
+1, for the using code example...
Mitch Wheat
The using statement, because who ever remembers to .Dispose() ?
Chris Ballance
+1  A: 

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.

Lou Franco
+2  A: 

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.

Mitch Wheat
Sorry if this is a duplicate. I didn't see anything that related to this specific case and was curious what (if any) unmanaged resources would be used in this case.
alnorth29
A: 

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 
}
Brian Rasmussen