gpt4 book ai didi

c# - 采用 IDisposable 模式

转载 作者:太空宇宙 更新时间:2023-11-03 16:05:53 28 4
gpt4 key购买 nike

好的,我已经阅读了一些关于 IDisposable 最佳实践的文章,我想我基本上明白了(终于)。

我的问题与从 IDisposable 基类继承有关。我看到的所有示例都在子类中一遍又一遍地编写相同的代码块,但我看不出有什么好处。

为什么不简单地将一个虚方法放入基类中,在适当的时间从(私有(private)实现的)IDisposable 例程中调用它,这样子类就不会那么困惑,但仍然有机会做管理他们的资源?

我建议的基类:

public abstract class DreamDisposableBase : IDisposable
{
private bool _disposed = false;


protected virtual void LocalDispose(bool disposing)
{
}

~DreamDisposableBase()
{
// finalizer being called implies two things:
// 1. our dispose wasn't called (because we suppress it therein)
// 2. we don't need to worry about managed resources; they're also subject to finalization

// so....we need to call dispose with false, meaning dispose but only worry about *unmanaged* resources:

dispose(false);
}


void IDisposable.Dispose()
{
dispose(true); // true argument really just means that we're invoking it explicitly
}


private void dispose(bool disposing)
{
if (!_disposed)
{
// give sub-classes their chance to release their resources synchronously
LocalDispose(disposing);

if (disposing)
{
// true path is our cue to release our private heap variables...
}

// do stuff outside of the conditional path which *always* needs to be done - release unmanaged resources

// tell .net framework we're done, don't bother with our finalizer -
GC.SuppressFinalize(this);

// don't come back through here
_disposed = true;
}
}

}

最佳答案

我不希望每个类型都有终结器。很少需要在终结器中执行任何工作。如果 disposing 为真,几乎所有的实现都不会做任何事情。终结器会影响性能,因为它们会导致升级到 Gen2,需要清理两个集合并且调用终结器是单线程的。

大多数类不包装非托管资源,如果它们包装它们,则它们应该使用 SafeHandle 类型或其他类型。这也使得终结器变得不必要了。

关于c# - 采用 IDisposable 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19450064/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com