2015-11-13 66 views
1
public CategorieEquipement Select(int NoType) 
{ 
     SqlConnection cx = new SqlConnection(WebConfigurationManager.ConnectionStrings["SQLConnect"].Connection String); 
     SqlDataReader reader; 

     CategorieEquipement lstCategorie = new CategorieEquipement(); 
     try 
     { 
      cx.Open(); 
      SqlCommand com = new SqlCommand("SELECT_CategorieEquip", cx); 
      com.CommandType = System.Data.CommandType.StoredProcedure; 
      com.Parameters.AddWithValue("@where",NoType); 
      reader = com.ExecuteReader(); 

      while (reader.Read()) 
      { 
       lstCategorie.CodeRef = reader["CodeRef"].ToString(); 
      } 
     } 
     catch (Exception ex) 
     { 
      Debug.WriteLine("SELECT ERROR : " + ex.ToString()); 
      return null; 
     } 
     finally 
     { 
      if (cx != null) 
      { 
       cx.Close(); 
      } 
     } 
     return lstCategorie; 
    } 
} 

我的問題是,如果我刪除了代碼塊,垃圾回收器會在處理SQlConnection對象時關閉連接嗎?SqlConnection是否使用此功能處理

我知道這是一個更好的做法是明確的,但我的同事不同意。

+1

你的同事是錯的 – Steve

+1

爲什麼不圍繞一個using(){}'包裝'Sql對象來利用自動配置.. GC並不總是立即要麼..我同意@Steve也許你需要不要依靠你的牛工給你提供有缺陷的建議/信息 – MethodMan

+0

爲什麼不把它保留下來,代碼似乎完全沒問題...... –

回答

2

處理 SQlConnection對象時垃圾收集器是否會關閉連接?

垃圾收集器是不負責的對象上調用Dispose,通常Dispose是所謂的終結,只有GC將能夠妥善處置對象。需要注意的

一個重要的事情是,你無法預測何時垃圾收集過程將運行,所以它始終是更好地明確釋放對象(實現IDisposable

就數據庫連接而言,該方法應儘可能遲並儘可能早地關閉。

在上面cx.Close();的情況下應該是足夠了,相反,你也可以撥打cx.Dispose但更好的方法將封閉SqlConnectionusing statement塊。

這將轉化爲try/finally塊,它將確保SqlConnection處置。

1

垃圾收集會處理它,但由於它是非確定性的,你不知道它何時會這樣做。

C#提供using結構處置非託管代碼,並建議使用它:

using (SqlConnection cx = new SqlConnection(WebConfigurationManager.ConnectionStrings["SQLConnect"].ConnectionString);) 
{ 

} 

告訴你的同事,他們應該來包裝實現在using所以IDisposable接口對象的任何實例它們將以確定性的方式進行處理,以確保對應用程序資源的正確管理並避免內存泄漏等問題。