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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With