MemoryStream.Close() or MemoryStream.Dispose()

后端 未结 10 604
北海茫月
北海茫月 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:56

    None of the above. You needn't call either Close or Dispose.

    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 the MemoryStream object when your code no longer references the MemoryStream.

    If you have a long-lived reference to the MemoryStream, you can set that reference to null to allow the MemoryStream to be garbage collected. Close and Dispose free neither the steam buffer nor the MemoryStream object proper.

    Since neither Stream nor MemoryStream have a finalizer, there is no need to call Close or Dispose to cause GC.SuppressFinalize to be called to optimize garbage collection. There is no finalizer to suppress.

    The docs for MemoryStream put it this way:

    This type implements the IDisposable interface, but does not actually have any resources to dispose. This means that disposing it by directly calling Dispose() or by using a language construct such as using (in C#) or Using (in Visual Basic) is not necessary.

提交回复
热议问题