談C# using的用法與好處
之前的一篇文章中的代碼中有一個using的用法,剛開始查看了一些資料說是強(qiáng)制關(guān)閉對象的一個命令。今天又查了一些資料,才明白,原來using指令調(diào)用了一個方法——Dispose()方法。而Dispose()方法的作用就是釋放所有的使用資源。
例:
public void ExecuteCommand( string connString, string commandString ) { SqlConnection myConnection = new SqlConnection( connString ); SqlCommand mySqlCommand = new SqlCommand( commandString, myConnection ); myConnection.Open(); mySqlCommand.ExecuteNonQuery(); }
這個例子中的兩個可處理對象沒有被恰當(dāng)?shù)尼尫牛篠qlConnection和SqlCommand。兩個對象同時保存在內(nèi)存里直到析構(gòu)函數(shù)被調(diào)用。
解決這個問題的方法就是在使用完命令和鏈接后就調(diào)用它們的Dispose:
public void ExecuteCommand( string connString, string commandString ) { SqlConnection myConnection = new SqlConnection( connString ); SqlCommand mySqlCommand = new SqlCommand( commandString, myConnection ); myConnection.Open(); mySqlCommand.ExecuteNonQuery(); mySqlCommand.Dispose( ); myConnection.Dispose( ); }
使用using語句也可以很好的實現(xiàn)此功能,而且代碼很清晰:
public void ExecuteCommand( string connString, string commandString ) { using ( SqlConnection myConnection = new SqlConnection( connString )) { using ( SqlCommand mySqlCommand = new SqlCommand( commandString, myConnection )) { myConnection.Open(); mySqlCommand.ExecuteNonQuery(); } } }
當(dāng)你在一個函數(shù)內(nèi)使用一個可處理對象時,using語句是最簡單的方法來保證這個對象被恰當(dāng)?shù)奶幚淼簟.?dāng)這些對象被分配時,會被編譯器放到一個try/finally塊中。
SqlConnection myConnection = null; // Example Using clause: using ( myConnection = new SqlConnection( connString )) { myConnection.Open(); } // example Try / Catch block: try { myConnection = new SqlConnection( connString ); myConnection.Open(); } finally { myConnection.Dispose( ); }
有時候使用try/finally塊的時候會發(fā)現(xiàn)如果發(fā)生錯誤,程序不會報錯。本人感覺還是使用using語句比較好。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。
相關(guān)文章
C#并行編程之?dāng)?shù)據(jù)并行Tasks.Parallel類
這篇文章介紹了C#并行編程之?dāng)?shù)據(jù)并行Tasks.Parallel類,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05C#中Backgroundworker與Thread的區(qū)別
本文主要介紹了C#中Backgroundworker與Thread的區(qū)別,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06