NET中的资源分托管和非托管,所谓的托管是指CLR(通用语言运行时)中进行管理的资源,它可以由CLR自动进行内存回收. 也就是大家熟知的GC(垃圾回收机制). 而对于 非托管资源,比如数据库连接,COM连接等,那么需要手动清理回收资源. 清理非托管资源,我们可以用析构函数来执行,虽然它的执行时机不确定,但终究会被执行. 当然还有Dispose()和Close()方法,两者的区别在于,Close()后还要以用Open()打开,而Dispose()则是彻底销毁.
--- 使用析构函数时,需要GC.Collect()才会执行到(GC,Collect()在自动回收机制中会自动执行,也可以显式调用它) 而Dispose()需要显式地调用,或者使用using() ,但是,需要注意:在用析构函数时,至少分两步走:调用函数,回收内存. 那么,在用using()或*.Dispose()后,GC还会再去执行析构函数. 因此,在Dispose()里,加上GC.SupressFinalize(this)来防止再次调用析构函数.
总结: Dispose()和Close()需要显示调用,Dispose()可以通过using()调用.析构函数无法显式调用. Dispose()和析构函数是销毁对象,而Close()是关闭,可以通过Open()再开. 析构函数调用时机不确定,而Dispose()在显式或Using()时执行,Close()在显式时执行. 三者都是用来销毁非托管对象. 一段经典的C#-Dispose:









































