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 c开发者_运维技巧reated (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)?
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.
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.
MemoryStream
implements IDisposable
so when possible, use a using statement.
When that isn't feasible, make it a try/catch/finally block.
In cases when you need to let the object pass out of the scope of your code (when using or try/catch/finally won't work), it becomes the responsibility of the caller to implement the explicit disposal.
See here Avoiding Problems with the Using Statement
Looked at the IL and using
does this:
try
{
}finally
{
((System.IDisposable)obj).Dispose();
}
Which means your stream will get disposed no matter what but the exception(if it occurs in the try block) will remain on the stack so it may crash you app if you don't take care.
So: "The reference on the MemoryStream object is therefore lost. Does this scenario need a try/finally-block (or using-statement)?" - Its the same
Now its really interesting what would happen if the Dispose method fails for some reason- you got an IE security hole:) Kidding:)
精彩评论