MemoryStream.Close() or MemoryStream.Dispose()

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

    As a first solution, it's recommended to use using statements wherever possible. This is described here: http://msdn.microsoft.com/en-us/library/yh598w02.aspx

    When the lifetime of an IDisposable object is limited to a single method, you should declare and instantiate it in the using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

    Coming to the question now, as others suggested in most .NET framework classes, there is no difference between Close() and Dispose() and it doesn't matter which of the two methods you call. You should call one but not both. However, there are exceptions.

    There are exceptions; for example, System.Windows.Forms.Form and System.Data.SqlClient.SqlConnection have different behavior for Close() and Dispose().

    For complete details, you can check here: https://blogs.msdn.microsoft.com/kimhamil/2008/03/15/the-often-non-difference-between-close-and-dispose/

提交回复
热议问题