天天看點

using 釋放資源

我們知道使用C#程式通路資料庫資源需要幾個步驟:建立連接配接,打開連接配接,通路資料庫,關閉連接配接,基本架構如下:

SqlConnection conn = new SqlConnection(connString)
try 
{
  conn.Open();
//省略通路資料庫代碼..
}
catch (Exception ex)
{
  throw ex;
}
finally
{
  conn.Close();
}      

資料庫連接配接通常建立在通常有限的伺服器資源,是以釋放之後要及時關閉。

在代碼中,finally塊中調用Close()方法釋放連接配接,確定即使沒有異常發生,連接配接诶也能被釋放。

using 語句兩個作用:

作為關鍵字,using可以導入命名空間。

作為C#語句,using可以釋放對象的占有的記憶體資源。

基本文法如下:

using(SqlConnection conn = new SqlConnection(connString))

 {

  //資料庫代碼操作

}

using語句允許使用者定義一個範圍,并在範圍末尾處釋放對象。

using可以主動釋放的對象都需要實作IDisable接口。

即使都實作了IDisable接口,也沒有必要全部使用using。我們隻對那些對系統性能有重要影響的對象進行using限定,而其他對象可以交給垃圾回收器處理。

(1)此類實作了接口IDisposable(這個接口隻有一個方法void Dispose()),當這個類在using中執行個體化的時候,using代碼塊結束時會自動調用這個類中實作了接口IDisposable的Dispose()方法。Dispose()方法中常用來做些釋放資源的動作。

看看下面的一個簡單的例子:

using System;  
  
class Program  
{  
    public static void Main(string[] args)  
    {  
        using (Test test = new Test())  
        {  
            Console.WriteLine("Disposable is open!");  
        }  
  
        Console.WriteLine("Disposable is none!");  
        Console.ReadKey();  
    }  
}  
  
public class Test:IDisposable  
{  
 
    #region IDisposable 成員  
  
    public void Dispose()  
    {  
        Console.WriteLine("Disposable is close!");  
    }  
 
    #endregion  
}      

輸出結果如下:

Disposable is open!
Disposable is close!
Disposable is none!      

轉載于:https://www.cnblogs.com/baixingqiang/p/5473516.html