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();
}
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With