Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to call Graphics.Dispose()?

Tags:

.net

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?

like image 276
alnorth29 Avatar asked Oct 15 '09 14:10

alnorth29


3 Answers

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.

like image 75
Mitch Wheat Avatar answered Nov 15 '22 06:11

Mitch Wheat


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...
}
like image 33
Chris Ballance Avatar answered Nov 15 '22 07:11

Chris Ballance


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.

like image 20
Fredrik Mörk Avatar answered Nov 15 '22 07:11

Fredrik Mörk