MemoryStream must be explicitely be disposed?

后端 未结 4 2071
别跟我提以往
别跟我提以往 2020-12-19 07:20

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 (Mem         


        
相关标签:
4条回答
  • 2020-12-19 07:59

    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.

    0 讨论(0)
  • 2020-12-19 08:01

    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.

    0 讨论(0)
  • 2020-12-19 08:05

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

    0 讨论(0)
  • 2020-12-19 08:14

    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.

    0 讨论(0)
提交回复
热议问题