我永远不会记住实现IDisposable接口的所有规则,因此我尝试提出一个基类来处理所有这些并使IDisposable易于实现.我只是想听听你的意见,如果这个实现是好的,或者你是否看到我可以改进的东西.该基类的用户应该从它派生,然后实现两个抽象方法ReleaseManagedResources()和ReleaseUnmanagedResources().所以这是代码:
public abstract class Disposable : IDisposable
{
private bool _isDisposed;
private readonly object _disposeLock = new object();
/// <summary>
/// called by users of this class to free managed and unmanaged resources
/// </summary>
public void Dispose() {
DisposeManagedAndUnmanagedResources();
}
/// <summary>
/// finalizer is called by garbage collector to free unmanaged resources
/// </summary>
~Disposable() { //finalizer of derived class will automatically call it's base finalizer
DisposeUnmanagedResources();
}
private void DisposeManagedAndUnmanagedResources() {
lock (_disposeLock) //make thread-safe
if (!_isDisposed) { //make sure only called once
try { //suppress exceptions
ReleaseManagedResources();
ReleaseUnmanagedResources();
}
finally {
GC.SuppressFinalize(this); //remove from finalization queue since cleaup already done, so it's not necessary the garbage collector to call Finalize() anymore
_isDisposed = true;
}
}
}
private void DisposeUnmanagedResources() {
lock (_disposeLock) //make thread-safe since at least the finalizer runs in a different thread
if (!_isDisposed) { //make sure only called once
try { //suppress exceptions
ReleaseUnmanagedResources();
}
finally {
_isDisposed = true;
}
}
}
protected abstract void ReleaseManagedResources();
protected abstract void ReleaseUnmanagedResources();
}
Run Code Online (Sandbox Code Playgroud)
spe*_*der 12
我无法真正评论您的代码的正确性,但我怀疑您是否会在继承树的基础上找到具有灵活性的Disposable类.当你想继承自己不拥有的东西时,它没什么用处.我认为IDispoasble是一个接口,因为可以使用它的许多不同的域.在继承层次结构的底部提供具体实现将是......限制.
| 归档时间: |
|
| 查看次数: |
2261 次 |
| 最近记录: |