当前位置: 代码迷 >> 综合 >> 「C#」析构函数、Dispose、IDisposable
  详细解决方案

「C#」析构函数、Dispose、IDisposable

热度:46   发布时间:2023-12-07 05:27:32.0

C#类一般默认不写析构函数,类由GC自动销毁回收

当类中引入了非托管的资源,GC是管不到这些非托管资源的。需要借助析构函数和IDispose.

如何操作呢:

引入了非托管资源的类需要基于IDispose接口,并实现其接口方法。

//来自 程序集 mscorlib
public interface IDisposable
{//// 摘要://     执行与释放或重置非托管资源关联的应用程序定义的任务。void Dispose();
}

 实际使用参考微软官方的例子:IDisposable 接口 (System) | Microsoft Docs

using System;
using System.ComponentModel;public class DisposeExample
{public class MyResource: IDisposable{// 非托管的资源unmanaged resource.private IntPtr handle;// 来自其他类的托管资源Other managed resource this class uses.private Component component = new Component();// Dispose是否已经被调用private bool disposed = false;// The class constructor.public MyResource(IntPtr handle){this.handle = handle;}// 实现IDisposable接口。// Do not make this method virtual.// 派生类不能重写此方法。A derived class should not be able to override this method.public void Dispose(){Dispose(true);// 手动执行了Dispose,即已经销毁了对象及对象内的托管与非托管资源了,就告诉GC就别再管了。GC.SuppressFinalize(this);}// true即手动执行了Dispose,false就是大概你忘了Disopose// 手动Dispose时,释放所有的资源// 执行析构时,就只管非托管的,托管资源交给GCprotected 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.component.Dispose();}// Call the appropriate methods to clean up// unmanaged resources here.// If disposing is false,// only the following code is executed.CloseHandle(handle);handle = IntPtr.Zero;// Note disposing has been done.disposed = true;}}// Use interop to call the method necessary// to clean up the unmanaged resource.[System.Runtime.InteropServices.DllImport("Kernel32")]private extern static Boolean CloseHandle(IntPtr handle);// 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.~MyResource(){// Do not re-create Dispose clean-up code here.// Calling Dispose(false) is optimal in terms of// readability and maintainability.Dispose(false);}}public static void Main(){// Insert code here to create// and use the MyResource object.}
}