0

Disposable 模式是基于每个类重新实现的模式。所以,我一直在寻找一种方法来概括它。几年前我遇到的问题是,即使你将它实现为类本身,你也不能从你的 Disposable 实现和另一个类中派生一个对象(C# 不支持多继承)。

问题是,您如何制定一种通用的方式来实现 Disposable 模式,这样您就不需要为每个实现 IDisposable 的类显式地编写它?

这是 Visual Studio (VS 2015) 为您生成的标准 Disposable 模式。

public class TestClass : IDisposable {
    #region IDisposable Support

    private bool disposedValue = false; // To detect redundant calls

    protected virtual void Dispose(bool disposing) {
        if (!disposedValue) {
            if (disposing) {
                // TODO: dispose managed state (managed objects).
            }

            // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
            // TODO: set large fields to null.

            disposedValue = true;
        }
    }

    // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
    // ~DisposeTest() {
    //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    //   Dispose(false);
    // }

    // This code added to correctly implement the disposable pattern.
    public void Dispose() {
        // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        Dispose(true);
        // TODO: uncomment the following line if the finalizer is overridden above.
        // GC.SuppressFinalize(this);
    }

    #endregion
}
4

1 回答 1

2

我的实现

所以,这是我想出的解决方案。

public class DisposeService<T> where T : IDisposable {
    private readonly T _disposee;
    public Action<T> ManagedAction { get; set; }
    public Action<T> UnmanagedAction { get; set; }

    public DisposeService(T disposee, Action<T> managedAction = null, Action<T> unmanagedAction = null) {
        _disposee = disposee;
        ManagedAction = managedAction;
        UnmanagedAction = unmanagedAction;
    }

    private bool _isDisposed;

    public void Dispose(bool isDisposing) {
        if (_isDisposed) return;
        if (isDisposing && ManagedAction != null) {
            ManagedAction(_disposee);
        }
        var hasUnmanagedAction = UnmanagedAction != null;
        if (hasUnmanagedAction) {
            UnmanagedAction(_disposee);
        }
        _isDisposed = true;
        if (isDisposing && hasUnmanagedAction) {
            GC.SuppressFinalize(_disposee);
        }
    }
}

此类允许您为实现 IDisposable 的类创建 DisposableService<> 成员。下面是一个示例,说明当您只有托管资源时如何使用它。

public class TestClass : IDisposable {
    protected readonly DisposeService<TestClass> DisposeService;
    private readonly SafeHandle _handle;

    public TestClass() {
        DisposeService = new DisposeService<TestClass>(this, ps => { if (_handle != null) _handle.Dispose(); });
        _handle = new SafeFileHandle(IntPtr.Zero, true);
    }

    public void Dispose() {
        DisposeService.Dispose(true);
    }
}

这个怎么运作

  • DisposeService 将在对象的 Dispose 上运行它的 Dispose。
  • DisposeService 的 dispose 将运行您在初始化(或在派生类中更新)时提供的托管和非托管操作。
  • 如果提供了 UnmanagedAction,GC.SuppressFinalize 将自动运行。
  • 始终确保创建 DisposableService<> 作为构造函数的第一个操作。

因此,这里是使用非托管资源使用此服务的示例。

public class TestClass : IDisposable {
    protected readonly DisposeService<TestClass> DisposeService;
    private readonly SafeHandle _handle;

    public TestClass() {
        DisposeService = new DisposeService<TestClass>(this,
            ps => { if (_handle != null) _handle.Dispose(); },
            ps => { /* Free unmanaged resources here */ });
        _handle = new SafeFileHandle(IntPtr.Zero, true);
    }

    public void Dispose() {
        DisposeService.Dispose(true);
    }

    ~TestClass() {
        DisposeService.Dispose(false);
    }
}

并且,从上面的类创建派生类的示例。

public class TestClassDerived : TestClass, IDisposable {
    private readonly SafeHandle _derivedHandle;

    public TestClassDerived() {
        // Copy the delegate for the base's managed dispose action.
        var baseAction = DisposeService.ManagedAction;
        // Update the managed action with new disposes, while still calling the base's disposes.
        DisposeService.ManagedAction = ps => {
            if (_derivedHandle != null) {
                _derivedHandle.Dispose();
            }
            baseAction(ps);
        };
        _derivedHandle = new SafeFileHandle(IntPtr.Zero, true);
    }
}

易榨柠檬汁。您保留对基类委托的引用并将其作为派生类委托的一部分调用。

总的来说,应该比管理微软自 2005 年以来一直提供的 blarg 程序区域更干净......

编辑:我认为在构造函数中传递的“this”可能是一个问题。但是,它似乎不是:将“this”作为参数传递是一种不好的做法吗?请记住在您的操作中放置空检查,这样您就不会尝试处置空的东西。:-)

于 2015-09-04T21:05:18.520 回答