How do you prevent IDisposable from spreading to all your classes?

后端 未结 7 665
抹茶落季
抹茶落季 2020-12-07 10:28

Start with these simple classes...

Let\'s say I have a simple set of classes like this:

class Bus
{
    Driver busDriver = new Driver();
}

class          


        
7条回答
  •  时光说笑
    2020-12-07 10:46

    To prevent IDisposable from spreading, you should try to encapsulate the use of a disposable object inside of a single method. Try to design Shoelace differently:

    class Shoelace { 
      bool tied = false; 
    
      public void Tie() {
    
        using (var waitHandle = new AutoResetEvent(false)) {
    
          // you can even pass the disposable to other methods
          OtherMethod(waitHandle);
    
          // or hold it in a field (but FxCop will complain that your class is not disposable),
          // as long as you take control of its lifecycle
          _waitHandle = waitHandle;
          OtherMethodThatUsesTheWaitHandleFromTheField();
    
        } 
    
      }
    } 
    

    The scope of the wait handle is limited to the Tiemethod, and the class doesn't need to have a disposable field, and so won't need to be disposable itself.

    Since the wait handle is an implementation detail inside of the Shoelace, it shouldn't change in any way its public interface, like adding a new interface in its declaration. What will happen then when you don't need a disposable field anymore, will you remove the IDisposable declaration? If you think about the Shoelace abstraction, you quickly realize that it shouldn't be polluted by infrastructure dependencies, like IDisposable. IDisposable should be reserved for classes whose abstraction encapsulate a resource that calls for deterministic clean up; i.e., for classes where disposability is part of the abstraction.

提交回复
热议问题