Which one do I call?
Is it necessary to call both?
Will the other throw an exception if I have already called one of them?
Which one do I call?
Is it necessary to call both?
Will the other throw an exception if I have already called one of them?
Close()
andDispose()
, when called on aMemoryStream
, only serve to do two things:MemoryStream
does not have any unmanaged resources to dispose, so you don't technically have to dispose of it. The effect of not disposing aMemoryStream
is roughly the same thing as dropping a reference to abyte[]
-- the GC will clean both up the same way.The
Dispose()
method of streams delegate directly to theClose()
method2, so both do exactly the same thing.The documentation for
IDisposable.Dispose()
specifically states it is safe to callDispose()
multiple times, on any object3. (If that is not true for a particular class then that class implements theIDisposable
interface in a way that violates its contract, and this would be a bug.)All that to say: it really doesn't make a huge difference whether you dispose a
MemoryStream
or not. The only real reason it hasClose
/Dispose
methods is because it inherits fromStream
, which requires those methods as part of its contract to support streams that do have unmanaged resources (such as file or socket descriptors).1 Mono's implementation does not release the
byte[]
reference. I don't know if the Microsoft implementation does.2 "This method calls Close, which then calls Stream.Dispose(Boolean)."
3 "If an object's Dispose method is called more than once, the object must ignore all calls after the first one."
Calling only
Dispose()
will do the trick =)Calling Close() will internally call Dispose() to release the resources.
See this link for more information: msdn
None of the above. You needn't call either
Close
orDispose
.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 theMemoryStream
object when your code no longer references theMemoryStream
.If you have a long-lived reference to the
MemoryStream
, you can set that reference to null to allow theMemoryStream
to be garbage collected.Close
andDispose
free neither the steam buffer nor theMemoryStream
object proper.Since neither
Stream
norMemoryStream
have a finalizer, there is no need to callClose
orDispose
to causeGC.SuppressFinalize
to be called to optimize garbage collection. There is no finalizer to suppress.The docs for MemoryStream put it this way: