2016-08-08 14 views
-1

我懷疑在相同的代碼塊中以不同的方式應用「使用」語句會產生什麼顯着差異,這將是很好的知道實踐最好的方法爲我 sameple 1碼塊在「使用」語句內啓動sql對象和使用語句裝飾之間的區別

using (SqlConnection SqlConnection = new SqlConnection(dbConnectionString)) 
       { 
        SqlConnection.Open(); 
        using (var command = new SqlCommand(store_procName, SqlConnection)) 
        { 
         command.Parameters.Add(Constants.PARAM_Value, SqlDbType.VarChar).Value = Id; 
         command.CommandType = CommandType.StoredProcedure; 
         using (var adp = new SqlDataAdapter(command)) 
         { 
          adp.Fill(dtValid); 
         } 
        } 
       } 
       return dtValid; 

示例代碼塊2

using (SqlConnection SqlConnection = new SqlConnection(dbConnectionString)) 
       { 
        SqlConnection.Open(); 
        SqlCommand command = new SqlCommand(store_procName, SqlConnection);      
        command.Parameters.Add(Constants.PARAM_Value, SqlDbType.VarChar).Value = Id; 
        command.CommandType = CommandType.StoredProcedure; 
        SqlDataAdapter adp = new SqlDataAdapter(command); 
        adp.Fill(dtValid);      

       } 
       return dtValid; 
+3

這不是'asp.net-mv'c特定或'sql-serve'r特定問題。只是c#。另外,請在發佈前花費額外10秒的時間來格式化代碼以提高可讀性。 :) – Shyju

+0

其實我在MVC框架工作認爲有些人可能會遇到這種情況 –

+0

看看http://stackoverflow.com/questions/3715126/what-is-meant-by-connection-dispose-in-c –

回答

1

using語句是語法糖,而無需編寫到第釋放資源(例如,存儲器或把手) e代碼自己。所以一個代碼片段像

using (var adp = new SqlDataAdapter(command)) 
{ 
    adp.Fill(dtValid); 
} 

轉換成東西

SqlAdapter adp = null; 
try 
{ 
    adp = new SqlDataAdapter(command); 
    adp.Fill(dtValid); 
} 
finally 
{ 
    if (adp != null) adp.Dispose(); 
    // or rather (adp as IDisposable)?.Dispose(); 
} 

(這只是一個例子給你的想法,不一定由編譯器產生的確切的代碼)。

因此,如果您在代碼中省略了內部using聲明,則此時不會調用實例的Dispose()方法。最終垃圾收集將清理那些對象(通常導致調用Dispose())。

如果您對此方法進行大量調用並讀取大量數據以使SqlCommandSqlDataAdapter消耗大量資源,則區別是相關的。如果你想盡快釋放這些資源,你應該在using聲明中包含代碼。

您正在尋找最佳實踐(這通常是一個有趣的問題)。在大多數情況下,第一個片段(包含所有using聲明)是可取的,因爲它會立即釋放不再需要的所有資源。