C#中IDisposable
C#中IDisposable
在Net中,由GC垃圾回收线程掌握对象资源的释放,程序员无法掌控析构函数的调用时机。对于一些非托管资源,比如数据库链接对象等,需要实现IDisposable接口进行手动的垃圾回收。那么什么时候使用Idisposable接口,以及如何使用呢?
一、IDisposable的接口定义如下
public interface IDisposable
{
// Summary:
// Performs application-defined tasks associated with freeing, releasing, or
// resetting unmanaged resources.
void Dispose();
}
二:IDisposable基本应用
1.定义一个实现了IDisposable接口的类
C# 代码 复制
public class CaryClass :IDisposable
{
public void DoSomething()
{
Console.WriteLine(“Do some thing…”);
}
public void Dispose()
{
Console.WriteLine(“及时释放资源”);
}
}
2、两种方式来调用
(1)、使用Using语句会自动调用Dispose方法
using (CaryClass caryClass = new CaryClass())
{
caryClass.DoSomething();
}
(2)、现实调用该接口的Dispose方法
CaryClass caryClass = new CaryClass();
try
{
caryClass.DoSomething();
}
finally
{
IDisposable disposable = caryClass as IDisposable;
if (disposable != null)
disposable.Dispose();
}