When disposing bitmaps or not in .NET?

421 Views Asked by At

In many occasions I doubt if I need to dispose bitmaps objects. One scenario in which I doubt if it is necessary is the following when from within a method I have to return the bitmap:

private Bitmap SampleMethod(Bitmap bmpOriginal)
{
    BitmapData bmdo = null;
    Bitmap bm = null;
    BitmapData bmdn = null;

    try
    {
         bmdo = bmpOriginal.LockBits(new Rectangle(0, 0, bmpOriginal.Width, bmpOriginal.Height), ImageLockMode.ReadOnly, bmpOriginal.PixelFormat); 

         bm = new Bitmap(bmpOriginal.Width, bmpOriginal.Height, PixelFormat.Format1bppIndexed); 

         bmdn = bm.LockBits(new Rectangle(0, 0, bm.Width, bm.Height), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed); 

         // Do some things with bmdo and bmdn objects

         bm.UnlockBits(bmdn); 
         bmpOriginal.UnlockBits(bmdo); 
    }
    catch (Exception e)
    {
         if (bm != null) bm.Dispose();
    }

    return bm; 
}

What bmp objects do I need to dispose here, bmp? It's not clear for me. Also I have read articles where people do not recommend to dispose bitmaps that are being returned (that is the case).

2

There are 2 best solutions below

4
BWA On

If you dispose object it internal resources will be destroyed and object will be unusable. So if you return such object, you return unusable object.
Never dispose returned object, never mind what type.

And in catch

catch (Exception e)
{
     if (bm != null) bm.Dispose();
}

Set null for bm not to return a damaged object.

0
Christopher On

Your code is faulty. You are not disposing on a success, only on a failure. Use the finally block for disposing. Or better yet: use the using block. Even if that results in a using that is nested inside a try block.

If it implements IDisposeable, I would always dispose of it. Even if this implementation of the class does nothing there, another one might. And some classes (like Streams) can even encapsualte one another. While a memory stream is propably interally using a List - a managed resoruces that does not need disposing. Meahwile File and Network streams are the classical examples of stuff that must be Disposed. However a MemoryStream could encapsulate a FileStream too.

Classes might have optional fields that take disposeable resources. Just because you do not run into issues now, does not mean you will never. If it implements IDisposeable, asume you will propably need to call it.

But as BWA said, you can not dispose it in this code as you return it. So the code calling "SampleMethod" and getting the instance would be responsible for Disposing.