Is there any benefit to implementing IDisposable on classes which do not have resources?

后端 未结 11 2081
挽巷
挽巷 2020-12-14 05:14

In C#, if a class, such as a manager class, does not have resources, is there any benefit to having it : IDisposable?

Simple example:

pu         


        
11条回答
  •  时光取名叫无心
    2020-12-14 06:02

    There are only 2 reasons for implementing IDisposable on a type

    • The type contains native resources which must be freed when the type is no longer used
    • The type contains fields of type IDisposable

    If neither of these are true then don't implement IDisposable

    EDIT

    Several people have mentioned that IDisposable is a nice way to implement begin / end or bookended operations. While that's not the original intent of IDisposable it does provide for a very nice pattern.

    class Operation {
      class Helper : IDisposable {
        internal Operation Operation;
        public void Dispose() {
          Operation.EndOperation();
        }
      }
      public IDisposable BeginOperation() {
        ...
        return new Helper() { Operation = this };
      }
      private void EndOperation() {
        ...
      }
    }
    

    Note: Another interesting way to implement this pattern is with lambdas. Instead of giving an IDisposable back to the user and hoping they don't forget to call Dispose have them give you a lambda in which they can execute the operation and you close out the operation

    public void BeginOperation(Action action) {
      BeginOperationCore();
      try {
        action();
      } finally {
        EndOperation();
      }
    }
    

提交回复
热议问题