Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is calling MemoryStream.ToArray() dangerous after disposing?

Tags:

c#

stream

In the below code, is there any chance the GC will clean out the MemoryStream so that ToArray will fail, since it is outside the using statement?

private static byte[] getBytes()
{
    MemoryStream ms = null;

    using (ms = new MemoryStream())
    {
        // ...
    }

    return ms.ToArray();
}
like image 604
Kenoyer130 Avatar asked Oct 20 '10 18:10

Kenoyer130


People also ask

Do I need to close MemoryStream?

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.

Does MemoryStream copy byte array?

From expirience I can say, that it does not copy the array. Be aware though, that you are unable to resize the memory stream, when using an array in the constructor.


1 Answers

No, there's no chance of that. It's safe to do - the MemoryStream keeps a strong reference to the byte array.

I'll see if I can find any documentation about guarantees...

EDIT: Sort of...

From MemoryStream.Close:

The buffer is still available on a MemoryStream once the stream has been closed.

Admittedly that doesn't guarantee it for Dispose, but that's documented to call Stream.Close.

MemoryStream.Dispose(bool) could then be overridden to release the array, but it doesn't in my experience, and it would be a breaking change at this point.

like image 129
Jon Skeet Avatar answered Sep 18 '22 17:09

Jon Skeet