2009年12月4日 星期五

SQL Connection Dispose or Close

在asp裡開啟了資料庫連線,使用到最後,總要把連線關閉,只是connection.close()跟connection.dispose(),到底適合用在什麼時候,在google之後,找到相關的說明如下:

There seems to be a lot of confusion about how to clean up after using a SqlConnection object. Should you call Close(), Dispose(), Close() then Dispose(), or neither?

Here are some relevant facts we need to consider:


When an open SqlConnection goes out of scope, its underlying physical database connection will not be closed or returned to the connection pool by the garbage collector;
Dispose() always calls Close() implicitly;
Dispose() clears the ConnectionString, Close() does not;
In future versions of ADO.NET, the SqlConnection.Dispose method might free other unmanaged resources, in addition to the database connection.
What conclusions can we draw?


We must at least call Close() or Dispose(), otherwise the database connection won't be released;
There's no need to call both Close() and Dispose();
If we're going to open the connection again, we should Close() not Dispose();
When we're completely finished with the SqlConnection, we should call Dispose() to make sure that all unmanaged resources are released, both now and in the future.

The tempation of symmetry after calling Open() is to always call Close(), as was the case in classic ADO, but I've shown that in the case of SqlConnection we only need to call Dispose(). Better still, make sure Dispose() is always called implicitly by enclosing your SqlConnection objects in a using statement.


參考資料