Ray's playground

 

Item 17: Implement the Standard Dispose Pattern(Effective C#)

  The implementation of your IDisposable.Dispose() method is responsible for four tasks:
  1. Freeing all unmanaged resources.
  2. Freeing all managed resources (this includes unhooking events).
  3. Setting a state flag to indicate that the object has been disposed. You need to check this state and throw ObjectDisposed exceptions in your public methods, if any get called after disposing of an object.
  4. Suppressing finalization. You call GC.SuppressFinalize(this) to accomplish this task.
  Unless your class directly contains unmanaged resources, you should not implement a finalizer. Only those classes that directly contain an unmanaged resource should implement the finalizer and add that overhead. Even if it’s never called, the presence of a finalizer does introduce a rather large performance penalty for your types. Unless your type needs the finalizer, don’t add it. However, you should still implement the pattern correctly so that if any derived classes do add unmanaged resources, they can add the finalizer, and implement Dispose(bool) in such a way that unmanaged resources are handled correctly. 

posted on 2011-01-27 23:10  Ray Z  阅读(158)  评论(0编辑  收藏  举报

导航