C# using 实现强制资源清理

一、总述:

使用using语句,定义一个范围,在范围结束时处理对象 (该对象必须实现了IDisposable接口)。

其功能和try ,catch,finally完全相同。

二、用法: 
using (Class1 c = new Class1())
{
 
}//在范围结束时清理非托管不受GC控制的资源
 

其与下面的try…catch…finallya功能一样

Class1 f = new Class1();
try
{ //执行代码
}
catch()
{
//异常处理
}
finally
{

f.Disposable();

 
}
例如:

      

using (SqlConnection cn = new SqlConnection(SqlConnectionString)){......}//数据库连接
using (SqlDataReader dr = db.GetDataReader(sql)){......}//DataReader


//PS:这里SqlConnection和SqlDataReader对象都默认实现了IDisposable接口,如果是自己写的类,那就要自己手动来实现IDisposable接口。比如:
using (Employee emp = new Employee(userCode))
{
           //......
}
//Emlpoyee.cs类:       
public class Employee:IDisposable
{
       实现IDisposable接口#region 实现IDisposable接口
        /**//// <summary>
       /// 通过实现IDisposable接口释放资源
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        /**//// <summary>
        /// 释放资源实现
         /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
               if (disposing)
                {
                    // Release managed resources
                    if(db!=null)
                        this.db.Dispose();
                    if(dt!=null)
                        this.dt.Dispose();
                    this._CurrentPosition = null;
                    this._Department = null;
                    this._EmployeeCode = null;               
               }
                // Release unmanaged resources
                m_disposed = true;
            }
        }
        /**//// <summary>
        /// 析构函数
         /// </summary>
        ~Employee()
        {
            Dispose(false);
        }
        private bool m_disposed;
        #endregion
}      

原文地址:https://www.cnblogs.com/johnpher/p/2872908.html