MemoryStream.Close()或MemoryStream.Dispose()MemoryStream、Close、Dispose

2023-09-02 10:36:13 作者:못 잊어 (没能忘

哪一个我打电话?

是否需要通话双方?

请问对方抛出一个异常,如果我已经叫他们中的一个?

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

推荐答案

关闭()的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 是大致相同的事情,删除一个引用字节[] - 中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()方法直接将关闭()方法 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() 具体规定是安全的,叫的Dispose()多次,对任何对象 3 。 (如果这是不是真的对某一类那么这个类实现了违反了合同的方式的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 与否。唯一真正的原因,它具有关闭 / 处置方法是因为它从流,这就要求这些方法作为合同的一部分,以支持流了的执行的具有非托管资源(例如文件或套接字描述符)。

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's实施不释放字节[] 引用。我不知道,如果微软不执行

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

2 的此方法调用关闭,然后调用Stream.Dispose(布尔)。的

3 的如果对象的Dispose方法被调用一次以上,对象必须忽略在第一个之后的所有呼叫。的

 
精彩推荐
图片推荐