DB Connection 的Close與Dispose

或許有些人在使用DB Connection時,會有一個疑問,究竟最後是要把Connection給Close再Dispose,還是直接Dispose就好呢?Dispose時,Connection也會一同Close嗎?

 

或許有些人在使用DB Connection,會有一個疑問,究竟最後是要把ConnectionCloseDispose,還是直接Dispose就好呢?Dispose,Connection也會一同Close?

 

先把CloseDispose這兩個Method給分開來看,Close是把連線給關閉,Connection物件依然存在,所以是可以再Connection.Open來使用的,Dispose,就是把Connection執行個體所使用的Unmanaged資源給釋放,所以要再使用它就必需重新建立New一個執行個體出來.

 

到這裡大家都沒有什麼問題,問題在於呼叫Dispose,是否也會Close Connection? MSDN上所看到的答案是 : 會的!

MSDN 說明 :

If the SqlConnection goes out of scope, it won’t be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true of yes, the underlying connection is returned back to the connection pool. On the other hand, if Pooling is set to false or no, the underlying connection to the server is closed.

 

說真的,這幾年寫程式總是習慣先呼叫Close再呼叫Dispose,其實這也沒什麼錯,明確指令是比較好(誰知道會不會那天Framework更版也改了Dispose,就不會順便幫我們Close),當然,Using也是個不錯的用法,離開Using就會自動CloseDispose.

 

MSDN裡的說明,還有一段也是之前寫程式沒注意過的.因為我都是安份的自己RollBack,沒用Close玩過RollBack.

The Close method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled.

也就是說,當呼叫Close,如果還有一些未CommitTransaction,就會被RollBack.

雖然如此,我還是喜歡自己RollBack,避免未來造成閱讀困難.

 

       Connection.Close是否可在已經Close的情況下,再呼叫Close?答案是可以的,但如果是Connection.Open,就不可以在已經Open的情況下再次呼叫Open,這就會觸發Exception.

 

參考 :

MSDN SqlConnection.Close Method

MSDN Using Statement

使用Using來宣告Connection來Connection自動關閉回收,避免忘記回收關閉

物件Object的New,Dispose與Connection的Open,Close概念分享