Returning an object with an unbiased memory stream causes a memory leak?

I came across a routine that does something like this:

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

I am worried that this is not the best recommended approach. Does ms work correctly in this scenario?

Or would it be better to assign the result to a temporary bitmap, recycle 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 that “use” could be used in this scenario, but I'm not sure if it will behave correctly or not:

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

What is the most effective / correct solution? Thank!

+3
source share
1 answer

, , ms. Dispose , IDisposable.

. , using , , .

: -, return, try-finally ( using ), , , .

, using, , using, , , - , using.

.:

+2

Source: https://habr.com/ru/post/1783595/


All Articles