IDisposable pattern is expensively implemented. I counted 17 lines of code before I even actually began to manage resources.
Eric Lippert recently wrote a blog post , raising an interesting point: at any time when the finalizer starts, this is a mistake. I think that makes sense. If the IDisposable pattern is always respected, Finalizer should always be suppressed. He will never have a chance to escape. If we agree that starting the finalizer is a mistake, does it make sense to have a guide to get developers to get the next abstract class and prohibit the direct implementation of the IDisposable interface.
public abstract class AbstractDisaposableBase: IDisposable { ~AbstractDisaposableBase() { ReportObjectLeak(); Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected abstract void Dispose(bool disposing); [Conditional("DEBUG")] private void ReportObjectLeak() {
The benefits are obvious:
- The dispose implementation becomes simple and error-free , as shown below:
class MyClass1 : DisablableBase { protected override void Dispose(bool disposing) {
Remote object not reported
Always use a one-time template
But are there any problems with such a guide?
One possible problem is that each disposable object will have a finalizer defined. But since the finalizer is always suppressed, there should be no performance penalty.
What are your thoughts?
c # architecture finalizer disposable
Xiaoguo Ge
source share