问题描述
以下是我认为建议使用的典型IDisposable实现:
Here is the typical IDisposable implementation that I believe is recommended:
~SomeClass() {
Dispose(false);
}
public void Dispose() {
GC.SuppressFinalize(this);
Dispose(true);
}
protected virtual void Dispose(bool isDisposing) {
if(isDisposing) {
// Dispose managed resources that implement IDisposable.
}
// Release unmanaged resources.
}
现在,据我所知,终结器背后的想法是,如果我不要调用Dispose,我的非托管资源仍会正确释放。但是,据我所知,通常都同意不对实现IDisposable的对象调用Dispose可能是一个错误。
Now, to my understanding, the idea behind the finalizer there is that if I don't call Dispose, my unmanaged resources will be released properly still. However, to my knowledge, it is generally agreed upon that not calling Dispose on an object that implements IDisposable is probably a bug.
有没有特定的理由不完全接受它,而是这样做?
Is there a particular reason not to fully embrace this and do this instead?
~SomeClass() {
throw new NotImplementedException("Dispose should always be called on this object.");
}
public virtual void Dispose() {
GC.SuppressFinalize(this);
// Dispose managed resources that implement IDisposable.
// Release unmanaged resources.
}
推荐答案
从.NET 2.0开始,终结器中引发的未处理异常。
From .NET 2.0 and on, An unhandled Exception thrown in a Finalizer causes the process to terminate if the default policy is not overridden.
据我所知,终结器不是预期位置 >应该抛出异常的地方。我认为 Dispose()
方法有可能由于意外原因(线程中止,...)未被调用而仍然可以进行干净恢复,只要Finalizer能够正确执行。
To my understanding, a Finalizer is not an expected location where an Exception should be thrown. I think it is possible for a Dispose()
method not to have been called for an unexpected reason (Thread abort, ...) from which a clean recovery is still possible, provided that the Finalizer executes properly.
这篇关于在终结器中引发异常以强制执行Dispose调用:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!