MemoryStream must be explicitely be disposed?

╄→尐↘猪︶ㄣ 提交于 2019-11-29 10:50:07

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:)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!