C#Dispose的标准代码以及CloseHandle()函数的使用

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.
 // 提供给外部用户显示调用的方法,实际操作是在类的带参数的虚函数Dispose(bool disposing)中实现
 public void Dispose()
 {
  // 表示用户显示调用
  Dispose(true);
  // Take yourself off the Finalization queue
  // to prevent finalization code for this object
  // from executing a second time.
  // 由于用户是显示调用,所以资源释放不再由GC来完成
  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.
  // 表示本次调用是隐式调用,由Finalize方法调用,即托管资源释放由GC来完成
  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.
 }
  // 重写Dispose方法,释放派生类自己的资源,并且调用基类的Dispose方法
 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);
   }
  }
 }
}
// 在这里,派生类没有实现~MyResourceWrapper和public Dispose方法,应为他们已经继承了基类的这些特性,这也是我说本示例代码精要之处,他使用到了多态性原理,下面我会简单分析
// This derived class does not have a Finalize method
// or a Dispose method without parameters because it inherits

// them from the base class.


1,线程和线程句柄(Handle)不是一个东西,线程是在cpu上运行的.....(说不清楚了),线程句柄是一个内核对象。我们可以通过句柄来操作线程,但是线程的生命周期和线程句柄的生命周期不一样的。线程的生命周期就是线程函数从开始执行到return,线程句柄的生命周期是从CreateThread返回到你CloseHandle()。

2,所有的内核对象(包括线程Handle)都是系统资源,用了要还的,也就是说用完后一定要closehandle关闭之,如果不这么做,你系统的句柄资源很快就用光了。

3,如果你CreateThread以后需要对这个线程做一些操作,比如改变优先级,被其他线程等待,强制TermateThread等,就要保存这个句柄,使用完了在CloseHandle。如果你开了一个线程,而不需要对它进行如何干预,CreateThread后直接CloseHandle就行了。


所以CloseHandel(ThreadHandle );
只是关闭了一个线程句柄对象,表示我不再使用该句柄,即不对这个句柄对应的线程做任何干预了。并没有结束线程。CloseHandle的功能是关闭一个打开的对象句柄,该对象句柄可以是线程句柄,也可以是进程、信号量等其他内核对象的句柄,而ExitThread的功能是终止一个线程,它所接受的参数是一个线程的退出码。 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 中,实现 `IDisposable` 接口可以让对象在被使用完毕后进行资源释放。下面是一个示例: ```csharp using System; class MyClass : IDisposable { private bool disposed = false; // 执行资源清理的方法 protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { // 释放托管资源 } // 释放非托管资源 disposed = true; } } // 实现 IDisposable 接口 public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // 析构函数 ~MyClass() { Dispose(false); } } ``` 在上面的示例中,`Dispose` 方法是实现资源清理的关键所在。`Dispose` 方法接收一个布尔类型的参数 `disposing`,用于判断是否需要释放托管资源。当 `disposing` 为 `true` 时,表示需要释放托管资源和非托管资源,这是在调用 `Dispose` 方法时常用的方式;当 `disposing` 为 `false` 时,表示只需要释放非托管资源,这是在析构函数中常用的方式。 在 `Dispose` 方法中,判断当前对象是否已经释放过资源,如果没有释放过,则根据 `disposing` 的值释放资源,并将 `disposed` 标记为 `true`,表示对象已经被释放过。同时,在 `Dispose` 方法中还调用了 `GC.SuppressFinalize` 方法,表示不再调用对象的析构函数。 在类中实现 `IDisposable` 接口后,使用该类时,应该在使用完该对象之后调用 `Dispose` 方法来释放资源。也可以使用 `using` 语句来自动释放资源,如下所示: ```csharp using (var obj = new MyClass()) { // 使用 obj 对象 } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值