清理非托管资源

清理非托管资源

类型的 Dispose 方法应释放它拥有的所有资源。它还应该通过调用其父类型的 Dispose 方法释放其基类型拥有的所有资源。该父类型的 Dispose 方法应该释放它拥有的所有资源并同样也调用其父类型的 Dispose 方法,从而在整个基类型层次结构中传播此模式。若要确保始终正确地清理资源,Dispose 方法应该可以被多次调用而不引发任何异常。

为 System.GC.KeepAlive(System.Object) 方法提供的代码示例演示了强行垃圾回收如何在回收对象的成员仍在执行时引起终结器运行。在较长的 Dispose 方法末尾最好调用 KeepAlive 方法。

// Design pattern for the base class.

// By implementing IDisposable, you are announcing that instances

// of this type allocate scarce resources.

public class BaseResource: IDisposable

{

   // Pointer to an external unmanaged resource.

   private IntPtr handle;

   // Other managed resource this class uses.

   private Component Components;

   // Track whether Dispose has been called.

   private bool disposed = false;

 

   // Constructor for the BaseResource object.

   public BaseResource()

   {

      // Insert appropriate constructor code here.

   }

 

   // Implement IDisposable.

   // Do not make this method virtual.

   // A derived class should not be able to override this method.

   public void Dispose()

   {

      Dispose(true);

      // Take yourself off the Finalization queue

      // to prevent finalization code for this object

      // from executing a second time.

      GC.SuppressFinalize(this);

   }

 

   // Dispose(bool disposing) executes in two distinct scenarios.

   // If disposing equals true, the method has been called directly

   // or indirectly by a user's code. Managed and unmanaged resources

   // can be disposed.

   // If disposing equals false, the method has been called by the

   // runtime from inside the finalizer and you should not reference

   // other objects. Only unmanaged resources can be disposed.

   protected virtual void Dispose(bool disposing)

   {

      // Check to see if Dispose has already been called.

      if(!this.disposed)

      {

         // If disposing equals true, dispose all managed

         // and unmanaged resources.

         if(disposing)

         {

            // Dispose managed resources.

            Components.Dispose();

         }

         // Release unmanaged resources. If disposing is false,

         // only the following code is executed.

         CloseHandle(handle);

         handle = IntPtr.Zero;

         // Note that this is not thread safe.

         // Another thread could start disposing the object

         // after the managed resources are disposed,

         // but before the disposed flag is set to true.

         // If thread safety is necessary, it must be

         // implemented by the client.

 

      }

      disposed = true;        

   }

 

   // Use C# destructor syntax for finalization code.

   // This destructor will run only if the Dispose method

   // does not get called.

   // It gives your base class the opportunity to finalize.

   // Do not provide destructors in types derived from this class.

   ~BaseResource()     

   {

      // Do not re-create Dispose clean-up code here.

      // Calling Dispose(false) is optimal in terms of

      // readability and maintainability.

      Dispose(false);

   }

 

   // Allow your Dispose method to be called multiple times,

   // but throw an exception if the object has been disposed.

   // Whenever you do something with this class,

   // check to see if it has been disposed.

   public void DoSomething()

   {

      if(this.disposed)

      {

         throw new ObjectDisposedException();

      }

   }

}

 

// Design pattern for a derived class.

// Note that this derived class inherently implements the

// IDisposable interface because it is implemented in the base class.

public class MyResourceWrapper: BaseResource

{

   // A managed resource that you add in this derived class.

   private ManagedResource addedManaged;

   // A native unmanaged resource that you add in this derived class.

   private NativeResource addedNative;

   private bool disposed = false;

 

 // Constructor for this object.

   public MyResourceWrapper()

   {

      // Insert appropriate constructor code here.

   }

 

   protected override void Dispose(bool disposing)

   {

      if(!this.disposed)

      {

         try

         {

            if(disposing)

            {

               // Release the managed resources you added in

               // this derived class here.

               addedManaged.Dispose();        

            }

            // Release the native unmanaged resources you added

            // in this derived class here.

            CloseHandle(addedNative);

            this.disposed = true;

         }

         finally

         {

            // Call Dispose on your base class.

            base.Dispose(disposing);

         }

      }

   }

}

 

// This derived class does not have a Finalize method

// or a Dispose method without parameters because it inherits

// them from the base class.

如果您要编写代码,而该代码使用一个封装资源的对象,您应该确保在使用完该对象时调用该对象的 Dispose 方法。要做到这一点,可以使用 C# 的 using 语句,或使用其他面向公共语言运行库的语言来实现 try/finally 块。

using 语句允许程序员指定使用资源的对象应当何时释放资源。为 using 语句提供的对象必须实现 IDisposable 接口。此接口提供了 Dispose 方法,该方法将释放此对象的资源。

 

class myApp

{

   public static void Main()

   {

      using (ResourceWrapper r1 = new ResourceWrapper())

      {

         // Do something with the object.

         r1.DoSomething();

      }

   }

}

posted @ 2010-06-01 08:15  gege_s  Views(462)  Comments(0)    收藏  举报