Will it be a valid base class for IDisposable

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() { //Debug.Assert(false, "leaked instance"); //throw new Exception("leaked instance"); } } 

The benefits are obvious:

  • The dispose implementation becomes simple and error-free , as shown below:

class MyClass1 : DisablableBase { protected override void Dispose(bool disposing) { //dispose both managed and unmamaged resources as though disposing==true } } 
  1. Remote object not reported

  2. 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?

+7
c # architecture finalizer disposable
source share
2 answers

does it make sense to have a guide to get developers to get the next abstract class

No, just for the reason that C # does not have multiple inheritance. Interfaces describe behavior; inheritance dictates "is-a". You will completely limit the object-oriented design of your classes if you apply this rule.

For example, you cannot enter base classes for business objects that are not disposable, where the derived class will be.

+4
source share

But since the finalizer is always suppressed, there should be no performance penalty.

Subclasses of AbstractDisaposableBase subclasses will still be involved in managing the completion queue, so there will be a performance effect for this.

0
source share

All Articles