好的,我已经阅读了一些关于 IDisposable 最佳实践的内容,我认为我基本上明白了(最后)。
我的问题与从 IDisposable 基类继承有关。我看到的所有示例都在子类中一遍又一遍地编写相同的代码块,但我没有看到优势。
为什么不简单地将虚拟方法烘焙到基类中,在正确的时间从(私有实现的)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;
}
}
}