2010-02-22 12 views
1

我正在瀏覽ASP.NET應用程序中的一些舊的C#.NET代碼,確保使用塊確保所有SqlConnections都封裝在中。如果我在SqlConnection的using語句內部捕獲異常,那麼使用仍然處理關閉和處置我的連接?

這段代碼用於打開CN和關閉以及在兩個捕獲塊,並且該方法的結束處理它們。我加入了usings並不能找出某些如果使用塊還是處理連接的配置,如果有異常的拋出嘗試和夾在This question似乎表明它確實如此。

using (SqlConnection cn = new SqlConnection(Global.sDSN)) 
{ 
    using (SqlDataAdapter da = new SqlDataAdapter()) 
    { 
     // do some stuff 
     try 
     { 
      // do stuff that might throw exceptions 
     } 
     catch (catch (System.Exception e) 
     { 
      //return something here 
      // can I ditch these because the using's handle it?  
      da.Dispose(); 
      cn.Close(); 
      cn.Dispose(); 
      return msg; 
     } 
    } 
} 

回答

3

是的,他們會。他們基本上變成了finally塊。

因此,像這樣:

using (SqlConnection cn = new SqlConnection(Global.sDSN)) 
{ 
.... 
} 

真的變成:

SqlConnection cn = new SqlConnection(Global.sDSN) 
try 
{ 
.... 
} 
finally 
{ 
    cn.Dispose(); 
} 

更多或更少 - finally塊是總是執行的,不管是什麼可能已經發生過try {.....}塊。

1

當您使用using條款,這是發生了什麼事:

 
myobject = new object(); 
try{ 
    // do something with myobject 
}finally{ 
    myobject.Dispose(); 
} 

希望這有助於 最好的問候, 湯姆。

相關問題