Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Memory Stream from a method

Wanted to know if the below scenario will cause any memory leak.

Aspx page contains the below.

private void Generator(input)
{
    using (MemoryStream memoryStream = Helper.Instance.Generate(input))
    {
    }
}

Below method is called from the aspx page which returns memory stream.

MemoryStream Generate(input)
{
    MemoryStream stream = new MemoryStream();
    //doing some stream manipulation here

    return stream;
}
like image 227
Kannan Avatar asked Sep 18 '12 12:09

Kannan


People also ask

Should memory stream be disposed?

You needn't call either Close or Dispose . MemoryStream doesn't hold any unmanaged resources, so the only resource to be reclaimed is memory. The memory will be reclaimed during garbage collection with the rest of the MemoryStream object when your code no longer references the MemoryStream .

How do I reuse MemoryStream?

You can re-use the MemoryStream by Setting the Position to 0 and the Length to 0. By setting the length to 0 you do not clear the existing buffer, it only resets the internal counters.

What is the difference between memory stream and stream?

You would use the FileStream to read/write a file but a MemoryStream to read/write in-memory data, such as a byte array decoded from a string.

What is a memory stream?

MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.


1 Answers

  • First point: if an exception is thrown by the code at:

    // doing some stream manipulation here
    

    then the MemoryStream will not be returned by Helper.Instance.Generate, so will not be disposed by the caller.

  • Second point: MemoryStream doesn't use any unmanaged resources, so it isn't essential to call Dispose.

So in this case there will be no memory leak.

It would be arguably better to force a Dispose in Helper.Instance.Generate if an exception is thrown thus:

MemoryStream Generate(input)  
{      
    MemoryStream stream = new MemoryStream();      

    try
    {
        //doing some stream manipulation here        

        return stream;  
    }
    catch
    {
        stream.Dispose();
        throw;
    }
}  

This is a general pattern for methods that construct, manipulate and return an IDisposable object.

like image 132
Joe Avatar answered Sep 29 '22 16:09

Joe