SqlConnection - Close() or Dispose()

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.

原文连接:http://chrisfulstow.blogspot.com/2006/11/sqlconnection-close-or-dispose.html


con.close() 是关闭连接,实际上是把连接放回ado.net的连接池,并没有真正关闭,所以再次连接时只是把连接从池中拿出来用,速度很快。
con.dispose是用来释放对象的所在内存,相对于new sqlconnection();
只用dispose是不能关闭connection的,两者不是一回事,只用close也不能释放它所占的内存。
conn.dispose() 是销毁连接,彻底关闭。
本文来自: 脚本之家(www.jb51.net) 详细出处参考:http://www.jb51.net/article/16923.htm

你可能感兴趣的:(html,.net,脚本,UP)