MemoryStream.Close() or MemoryStream.Dispose()

2019-01-07 12:43发布

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条回答
男人必须洒脱
2楼-- · 2019-01-07 13:21

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.

查看更多
小情绪 Triste *
3楼-- · 2019-01-07 13:24

the following code is Stream.Dispose from reflector as you can see, you don't need to close if you dispose (which is implicit when using using)

public void Dispose()
{
    this.Close();
}
查看更多
走好不送
4楼-- · 2019-01-07 13:38

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/

查看更多
混吃等死
5楼-- · 2019-01-07 13:39

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.

查看更多
Fickle 薄情
6楼-- · 2019-01-07 13:40

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

查看更多
我欲成王,谁敢阻挡
7楼-- · 2019-01-07 13:41

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
查看更多
登录 后发表回答