简体   繁体   中英

Returning an Object with Non-Disposed Memory Stream causes memory leaks?

I've come across a routine that does something like this:

static public Bitmap byte2bmp(byte[] BitmapData)
{
    MemoryStream ms = new MemoryStream(BitmapData);
    return (new Bitmap(ms));
}

I'm worried this might not be the best recommended approach. Does the ms gets disposed properly in this scenario?

Or would it be better to assign the result to a temporary Bitmap, dispose of the stream, and then return the temp object?

static public Bitmap byte2bmp(byte[] BitmapData)
{
    MemoryStream ms = new MemoryStream(BitmapData);
    Bitmap temp=new Bitmap(ms);
    ms.Dispose();
    return (temp);
}

I was hoping the "using" might be used in this scenario, but am not sure it would behave properly or not:

static public Bitmap byte2bmp(byte[] BitmapData)
{
    using(MemoryStream ms = new MemoryStream(BitmapData))
    {
    return (new Bitmap(ms));
    }
}

What is the most effective/proper solution? Thanks!

You're correct in worrying that the first approach will fail to dipose ms . As a matter of good practice, you should always call the Dispose method on objects that implement IDisposable .

I recommend adopting the last approach. You can be confident that a using statement will dispose of the object as expected even if you return in the middle of it.

Here's how the code would break down during run time: First, the return expression will be evaluated, then the try-finally block (for which the using statement is simply syntactic sugar) will be executed, and finally the method will return.

The only case in which you might encounter issues with returning in the middle of a using statement is if you return the variable from the using statement itself . Of course, this would cause issues anyway if you retained any reference to the variable beyond the scope of the using block.

Also see: Best practice regarding returning from using blocks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM