MemoryStream.Close() or MemoryStream.Dispose()

后端 未结 10 563
北海茫月
北海茫月 2020-11-29 03:19

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?

相关标签:
10条回答
  • 2020-11-29 03:37

    You can use the using block for this. It will automatically call Dispose when it goes outside of its scope.

    Example:

    using (MemoryStream ms = new MemoryStream())
    {
        // Do something with ms..
    }
    // ms is disposed here
    

    Hope this helped.

    0 讨论(0)
  • 2020-11-29 03:39

    Use using block so that your object is disposed if its implements IDisposable interface

    0 讨论(0)
  • 2020-11-29 03:44

    In .NET 3.5 (haven't checked other versions), methods are called in the following order when disposing a MemoryStream:

    1. Stream.Dispose()
      • simply calls Close
    2. Stream.Close()
      • calls Dispose(true), then GC.SuppressFinalize(this)
    3. MemoryStream.Dispose(true)
      • sets _isOpen , _writable, and _expandable flags to false
    4. Stream.Dispose(true)
      • closes async event if active
    0 讨论(0)
  • 2020-11-29 03:47

    Calling only Dispose() will do the trick =)

    0 讨论(0)
  • 2020-11-29 03:49

    Which one do I call?

    Any of them.

    Is it necessary to call both?

    No, either one is sufficient.

    Will the other throw an exception if I have already called one of them?

    No, disposable pattern declares that subsequent calls to Dispose don't cause negative effects.

    0 讨论(0)
  • 2020-11-29 03:53

    Calling Close() will internally call Dispose() to release the resources.

    See this link for more information: msdn

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