Search code examples
c#gdi+dispose

When to Dispose of GDI Objects, Specifically Bitmaps


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

  1. 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);
    
  2. Because I want to keep bitmaps for the lifetime of the form, can I simply dispose of them on the form close event?

  3. 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!


Solution

    1. Yes You absolutely have to call "Dispose" in this case. Not doing so will leak the old memory.
    2. Any bitmaps that truly need to have form lifetime can be disposed in "Close". I would not do this for every bitmap though, as you will eat up memory quickly by having a lot of them in memory at the same time..
    3. That depends on your use case. If you are running some sort of animation, does the quality really need to be that good? Memory usage vs. speed. vs image quality, only you know what is the most important. You can't have all three though.

    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
    }