在处置(布尔)方法实现,不应该一组成员为空?布尔、为空、成员、方法

2023-09-04 00:44:26 作者:最初模样

没有一个讨论的IDisposable 模式建议,应该设置内部成员空在的Dispose(布尔)办法(特别是如果他们是内存占用的野兽)。

None of the guides/notes/articles that discuss IDisposable pattern suggest that one should set the internal members to null in the Dispose(bool) method (especially if they are memory hogging beasts).

我已经认识到它的重要性,同时调试一个内部基准测试工具。用什么来发生的是,有这个缓冲区包含一个大阵里面。我们习惯用一个静态缓冲区对于整个基准测试程序。一旦我们与缓冲完成的,没有办法,我们可以释放这个内部数组,无论我们能否使这个缓冲区释放的(因为它是静态的)。

I've come to realize the importance of it while debugging an internal benchmark tool. What used to happen was that, there was this buffer that contained a big array inside it. We used to use a static buffer for the whole benchmark program. Once we're done with the buffer, there was no way we could release this internal array, neither could we make this buffer releasable (as it was static).

所以,我相信,经过的Dispose()被调用,类应该竭尽所能,使其释放所有的资源,它是使用并使它们可再次,即使被布置在对象本身不收集回来通过GC,和不设置部件为空,由此,不使内部的对象通过GC进行收集意味着该处置实现是不完美的。

So, I believe that, after Dispose() is called, the class should do everything it can so that it releases all the resources it is using and make them available again, even if the object being disposed itself is not collected back by GC, and not setting members to null, thereby, not allowing the internal objects to be collected by the GC implies that the Dispose implementation is not perfect.

什么是你的意见呢?

推荐答案

处置释放任何额外的引用是肯定是我尝试做,有两个原因:

Releasing any additional references during Dispose is certainly something I try to do, for two reasons:

它允许内部的对象被垃圾收集,即使释放的对象仍处于范围 如果内部对象是一次性的,这意味着我们只即使处理他们曾经的Dispose()的外部对象上多次呼吁 it allows the inner objects to be garbage collected even if the disposed object is still in scope if the inner objects are disposable, it means we only dispose them once even if Dispose() is called repeatedly on the outer object

例如,我倾向于使用这样的话:

For example, I tend to use things like:

if(someDisposableObject != null)
{
    someDisposableObject.Dispose();
    someDisposableObject = null;
}
(for non-disposable, just set to null)
someNonDisposableObject = null; // etc

您可能还需要设置任何事件为空:

You might also want to set any events to null:

someEventHandler = null;

这可以帮助减少的影响,如果调用者无法充分释放他们的引用(或者干脆忘记了)的时刻。虽然你应该尝试释放外部对象(GC),这是比较容易通过捕获变量(匿名方法/λ),事件等意外延长对象的生命周期,例如。

This can help minimise the impact if the caller can't fully release their reference (or simply forgets) at the moment. While you should try to release the outer object (for GC), it is relatively easy to accidentally extend the life of the object, for example via a captured variable (anonymous method/lambda), an event, etc.

如果你有一个终结,然后在GC过程中有没有好处这样做,你不应该真正调用外部对象的方法(甚至的Dispose() ) - 因此,在短期:不要在一个GC扫做任何的这种

If you have a finalizer, then during the GC process there is no benefit doing this, and you shouldn't really call methods on external objects (even Dispose()) - so in short: don't do any of this during a GC sweep.