MemoryStream.Close() 或 MemoryStream.Dispose() [英] MemoryStream.Close() or MemoryStream.Dispose()

查看:67
本文介绍了MemoryStream.Close() 或 MemoryStream.Dispose()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该打电话给谁?

有必要同时调用吗?

如果我已经调用了其中一个,另一个会抛出异常吗?

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

推荐答案

Close()Dispose(),当在 MemoryStream,只为做两件事:

Close() and Dispose(), when called on a MemoryStream, only serve to do two things:

  • 将对象标记为已释放,以便将来意外使用该对象时会引发异常.
  • 可能1释放对托管对象的引用,这可以使 GC 的工作更容易一些,具体取决于 GC 实现.(在今天的 GC 算法中,它没有真正的区别,因此这是学术讨论的重点,对现实世界没有重大影响.)
  • Mark the object disposed so that future accidental usage of the object will throw an exception.
  • Possibly1 release references to managed objects, which can make the GC's job a bit easier depending on the GC implementation. (On today's GC algorithms it makes no real difference, so this is a point for an academic discussion and has no significant real-world impact.)

MemoryStream 没有任何非托管资源可供处置,因此您在技术上不必处置它.不释放 MemoryStream 的效果与删除对 byte[] 的引用大致相同——GC 将以相同的方式清理两者.

MemoryStream does not have any unmanaged resources to dispose, so you don't technically have to dispose of it. The effect of not disposing a MemoryStream is roughly the same thing as dropping a reference to a byte[] -- the GC will clean both up the same way.

我该打电话给谁?有必要同时调用吗?

Which one do I call? Is it necessary to call both?

直接委托的Dispose()方法到 Close() 方法2,所以两者都做同样的事情.

The Dispose() method of streams delegate directly to the Close() method2, so both do exactly the same thing.

如果我已经调用了其中一个,另一个会抛出异常吗?

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

IDisposable.Dispose() 的文档 特别声明在任何对象3 上多次调用 Dispose() 是安全的.(如果对于特定的类不是这样,那么该类以违反其约定的方式实现 IDisposable 接口,这将是一个错误.)

The documentation for IDisposable.Dispose() specifically states it is safe to call Dispose() multiple times, on any object3. (If that is not true for a particular class then that class implements the IDisposable interface in a way that violates its contract, and this would be a bug.)

说了这么多:不管你是否配置 MemoryStream 并没有太大的区别.它具有 Close/Dispose 方法的唯一真正原因是因为它继承自 Stream,这需要将这些方法作为其合同的一部分来支持流确实有非托管资源(例如文件或套接字描述符).

All that to say: it really doesn't make a huge difference whether you dispose a MemoryStream or not. The only real reason it has Close/Dispose methods is because it inherits from Stream, which requires those methods as part of its contract to support streams that do have unmanaged resources (such as file or socket descriptors).

1 Mono 的实现 不会释放 byte[] 引用.我不知道微软的实现是否有.

1 Mono's implementation does not release the byte[] reference. I don't know if the Microsoft implementation does.

2 这个方法调用Close,然后调用Stream.Dispose(Boolean)."

3 如果一个对象的 Dispose 方法被多次调用,则该对象必须忽略第一次之后的所有调用."

这篇关于MemoryStream.Close() 或 MemoryStream.Dispose()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆