Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MemoryStream must be explicitely be disposed?

As MemoryStream is an unmanaged resource does it always have to be disposed?

Given:

1) A method is invoked.
2) A MemoryStream object is created (MemoryStream ms = new MemoryStream();).
3) An exception occurs and is caught from the invoking classes.

The reference on the MemoryStream object is therefore lost. Does this scenario need a try/finally-block (or using-statement)?

like image 829
bonobo Avatar asked Nov 16 '10 15:11

bonobo


People also ask

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 a MemoryStream?

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.

What is the difference between Stream and MemoryStream?

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. You would not use a Stream in and of itself, but rather use it for polymorphism, i.e. passing it to methods that can accept any implementation of Stream as an argument.

Does StreamWriter dispose stream?

StreamWriter. Dispose() does close the underlying stream.


2 Answers

In general, all disposable objects must always be disposed.

However, MemoryStream doesn't actually need to be disposed, since it doesn't have any unmanaged resources. (It's just a byte[] and an int)
The only reason it's disposable in the first place is that it inherits the abstract Stream class, which implements IDisposable.

Note that every other stream must be disposed.

like image 100
SLaks Avatar answered Oct 10 '22 11:10

SLaks


Any type that implements IDisposable should have Dispose called on it either explicitly via a try/catch/finally block or via the using statement.

There are cases such as this where technically the MemoryStream does not need disposed, however to honor the interface and protect yourself from changes downstream Dispose should still be called.

like image 32
Aaron McIver Avatar answered Oct 10 '22 11:10

Aaron McIver