Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

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

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

Simple example:

public interface IBoxManager
{
 int addBox(Box b);
}

public class BoxManager : IBoxManager
{
 public int addBox(Box b)
 {
  using(dataContext db = new dataContext()){
   db.Boxes.add(b);
   db.SaveChanges();
  }
  return b.id;
 }
}

Will there be any benefit in memory use when using BoxManager if it also implements IDisposable? public class BoxManager : IBoxManager , IDisposable

For example:

BoxManager bm = new BoxManager();
bm.add(myBox);
bm.dispose();//is there benefit to doing this?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...