Returning a memory stream from a method

You need to know if the following scenario could cause a memory leak.

The Aspx page contains below.

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

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

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

    return stream;
}
+5
source share
4 answers
  • First point: if an exception is thrown by code:

    // doing some stream manipulation here
    

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

  • The second point: it MemoryStreamdoes not use unmanaged resources, so it is not necessary to call Dispose.

Thus, in this case there will be no memory leak.

It would be better to force Dispose in Helper.Instance.Generateif an exception is thrown:

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

    try
    {
        //doing some stream manipulation here        

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

, , IDisposable.

+7

, , Dispose.

, :

 private void Generator(input)
 {
    using (MemoryStream memoryStream = new MemoryStream())
    {
        Helper.Instance.Manipulate(memoryStream);
    }
 }
0

, , MemoryStream, DataTable,... . using -, , . .

. . , .

, using, . ( ), .

0

All Articles