I recently learned about the need to dispose of GDI objects because the GC doesn't take care of them like other objects in C#. I have bitmaps that I would like to be available for the lifetime of a form, but I'm unsure about a few things...
When recreating a bitmap object, do I need to dispose of the original object first? I'm thinking not, but I thought I'd check. For example:
// Global Bitmap bmp; // In form constructor... bmp = new Bitmap(source); // In a function... if(bmp != null) { bmp.Dispose bmp = null } bmp = new Bitmap(source2); // On paint (if bmp not null)... DrawImage(bmp, rectangle);
Because I want to keep bitmaps for the lifetime of the form, can I simply dispose of them on the form close event?
Is there a better alternative than preserving the bitmaps? Creating each bitmap from a file and disposing on paint performs too slowly. Using Image instead of Bitmap lowers the image quality.
Thanks in advance!
If you are going to use a Bitmap
temporarily, you should consider wrapping it in a using
block so it gets disposed automatically:
using (Bitmap myBitmap = new Bitmap(src))
{
//Do stuff with the temp bitmap
}