using System; using System.ComponentModel; // The following example demonstrates how to create // a resource class that implements the IDisposable interface // and the IDisposable.Dispose method. publicclass DisposeExample { //实现IDisposable的基类,通过实现此接口,就表明此类型的实例会分配非托管资源 publicclass MyResource: IDisposable { private IntPtr handle;//指向一个内部非托管资源的指针 private Component component =new Component();//类中使用的其他托管资源 privatebool disposed =false;//跟踪Dispose是否已经被调用 public MyResource(IntPtr handle) { this.handle = handle; } //实现IDisposable接口,不要让此方法virtual。派生类应该不允许override这个方法 publicvoid Dispose() { Dispose(true); //此对象将被Dispose方法清理掉,因此,你需要调用GC.SuppressFinalize方法来 //将此对象从需要终止的对象队列中移除,并且防止这个对象执行两次终止代码 GC.SuppressFinalize(this); } //若disposing为true,则方法被用户代码直接或间接调用。托管资源和非 //托管资源可以被释放。 //若disposing为false,则方法被运行时从解析器内部调用并且你不应该再应用其他对象, //只有非托管资源能被释放。 privatevoid Dispose(bool disposing) { // Check to see if Dispose has already been called. if(!this.disposed) {//检查Dispose是否已经被调用过了 if(disposing) {//若disposing为true,释放所有托管和非托管资源 component.Dispose(); // 在此处释放托管资源 } // 在这调用适当的方法来清理非托管资源, // 若disposing为false,则只有下面的代码会执行 CloseHandle(handle); handle = IntPtr.Zero; } disposed =true; } // Use interop to call the method necessary // to clean up the unmanaged resource. [System.Runtime.InteropServices.DllImport("Kernel32")] privateexternstatic Boolean CloseHandle(IntPtr handle); //这个解析器只在Dispose方法没有被调用时才运行,它为你的基类提供了解析的 //机会。在其派生类中不要提供解析器。 ~MyResource() { Dispose(false);//解析器内部调用,只释放非托管资源,托管资源由垃圾回收器负责 } } publicstaticvoid Main() { // Insert code here to create // and use the MyResource object. } }