C#实现IDispose接口
.net的GC机制有两个问题:首先GC并不能释放所有资源,它更不能释放非托管资源。其次,GC也不是实时的,所有GC存在不确定性。
为了解决这个问题donet提供了析构函数
public class TestClass : System.IDisposable
{
//供程序员显式调用的Dispose方法
public void Dispose()
{
//调用带参数的Dispose方法,释放托管和非托管资源
Dispose(true);
//手动调用了Dispose释放资源,那么析构函数就是不必要的了,这里阻止GC调用析构函数
System.GC.SuppressFinalize(this);
} //protected的Dispose方法,保证不会被外部调用。
//传入bool值disposing以确定是否释放托管资源
protected void Dispose(bool disposing)
{
if (disposing)
{
///TODO:在这里加入清理"托管资源"的代码,应该是xxx.Dispose();
}
///TODO:在这里加入清理"非托管资源"的代码
} //供GC调用的析构函数
~TestClass()
{
Dispose(false);//释放非托管资源
}
}
而即使我们忘记了在合适的时候调用Dispose,GC也会在释放对象的时候帮我们清理非托管资源的。GC所充当的角色只是一种保障手段,它应该充当这种角色,我们不能过分依赖它。实际上,在较大的模块退出时我们还应该及时地手动调用GC.Collect进行垃圾回收。
为什么实现IDisposable接口的类的对象,因为.net CLR是采用GC(垃圾回收器)机制管理内存,不想C++语言那样,能保证对象的析构函数在作用域结束时被总是被自动调用,有时如果程序运行的过程中一直没有满足启动GC的条件,则可能GC一次也没启动。 这样,如果一个类需要占用重要资源,就应该实现IDisposable接口,或者使用另一种简捷的方式:使用Using,如:
Using(MyClass myObj = new MyClass())
{ ... }
对于没有实现IDisposable接口的,也就没什么Dispose方法,但他们的Finalize同样不能保证被调用。
Using(MyClass myObj = new MyClass())
{ ... }
是一种好方法,但是只有MyClass实现了IDisposable接口才能这样写.
IDispose模式在C++中用的很多,用来清理资源,而在C#里,资源分为托管和非托管两种,托管资源是由C#的CLR帮助我们清理的,它是通过调用对象的析构函数完成的对象释放工作,而对于非托管系统来说,则需要我们自己来释放,例如数据库连接对象,这就需要我们手动去调用它的Dispose()方法来实现对象它的释放,事实上,Dispose()内容到底做了什么事,我们并不清楚,当然这就是面向对象,它不希望你关系实现的细节,呵!
对于我们开发人员来说,在了解它怎么用之后,总会对它如何实现的产生兴趣,下面,我将把C#里实现IDispose模式的代码展现出来,大家一起来学习一下,事实上,它的使用场合也很多的,当我们手动对网站,数据库作封装时,都会用的到,下面看一下代码:
/// <summary>
/// 实现IDisposable,对非托管系统进行资源回收
/// </summary>
public class IDisplosePattern : IDisposable
{
public void Dispose()
{
this.Dispose(true);////释放托管资源
GC.SuppressFinalize(this);//请求系统不要调用指定对象的终结器. //该方法在对象头中设置一个位,系统在调用终结器时将检查这个位
} protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)//_isDisposed为false表示没有进行手动dispose
{
if (disposing)
{
//清理托管资源
}
//清理非托管资源
}
_isDisposed = true;
} private bool _isDisposed; ~IDisplosePattern()
{
this.Dispose(false);//释放非托管资源,托管资源由终极器自己完成了
}
}
通过上面的代码,我们知道了,对于托管系统(C#的CLR为我们管理的),直接通过~IDisplosePattern()方法进行释放,而~IDisplosePattern()这个方法何时被调用,我们是不知道的,因为它是由CLR帮助我们调用的,而我们手动进行dispose方法时,它会调用dispose(true)这个重载方法,它会帮助我们清理托管和非托管资源,如图:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAdoAAACrCAIAAABOj8ooAAAPNklEQVR4nO3d4W3qPBTGcS/iUbyMJ2GAqBswQxfIt3eL7hFV1a3a90NJ4tjHjgPh4MD/p+qKmtgxmD6cmsI1AwCgAebREwAADANxDACNII4BoAnEMQA0gTgGgCYQxwDQBOIYAJpAHANAE6ri+NcYvl7w694PvquZUytzu2UmU19zMuHX1hOFV4Vj3jjb1SldMSbKauP43vPAXV3xM9Paoouh83DllEy/xO41N60yEwtxvJr+lc8Kaa/CxLDJdXH85cx3Fx/15ca6yvrP9UE7Z32/+N4sGwo9jUvOvtR7a2bLoyu631nv7Typ3rvCzf7w9pxMVmyMde4030z5Z+bD2+DHz/236P5rzIPvpXdrTouVKpd+wzAMQ+fGm2Pfs/dq/27NyUSD1xNzdrWKLA+Yu1z+Wp2YOO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