The following code illustrates how to implement both the Dispose and Finalize pattern for a class.
   public class Base: IDisposable
  {
    private bool isDisposed = false;
 
     public void Dispose()
     {
        Dispose(true);
        GC.SuppressFinalize(this);
     }
     protected virtual void Dispose(bool disposing)
     {
        if(!isDisposed)
        {
         if (disposing)
         {
            // Code to dispose the managed resources
            // held by the class
         }
        }     
       // Code to dispose the unmanaged resources
       // held by the class
      isDisposed = true;
      base.Dispose(disposing);
     }
     ~Base()
     {
        Dispose (false);
     }
  }
   public class Base: IDisposable
  {
    private bool isDisposed = false;
 
     public void Dispose()
     {
        Dispose(true);
        GC.SuppressFinalize(this);
     }
     protected virtual void Dispose(bool disposing)
     {
        if(!isDisposed)
        {
         if (disposing)
         {
            // Code to dispose managed resources
            // held by the class
         }
        }     
       // Code to dispose unmanaged resources
       // held by the class
      isDisposed = true;
      base.Dispose(disposing);
     }
     ~Base()
     {
        Dispose (false);
     }
  }
 
  public class Derived: Base
  {  
     protected override void Dispose(bool disposing)
     {
        if (disposing)
        {
           // Code to cleanup managed resources held by the class.
        }
          
        // Code to cleanup unmanaged resources held by the class.
       
       base.Dispose(disposing);
     }
  // Note that the derived class does not // re-implement IDisposable
  }
Note the following points when implementing disposable types:
- Implement IDisposable on every type that has a finalizer
- Ensure that an object is made unusable after making a call to the Dispose method. In other words, avoid using an object after the Dispose method has been called on it.
- Call Dispose on all IDisposable types once you are done with them
- Allow Dispose to be called multiple times without raising errors.
- Suppress later calls to the finalizer from within the Dispose method using the GC.SuppressFinalize method
- Avoid creating disposable value types
- Avoid throwing exceptions from within Dispose methods
 
 
 
No comments:
Post a Comment