如何强制SqlConnection物理关闭,而使用连接池? [英] How to force a SqlConnection to physically close, while using connection pooling?
问题描述
我明白,如果我实例化一个SqlConnection对象,我真的抓住连接池的连接。当我调用Open(),它将打开连接。如果我对该SqlConnection对象调用Close()或Dispose()方法,它将返回到连接池。
I understand that if I instantiate a SqlConnection object, I am really grabbing a connection from a connection pool. When I call Open(), it will open the connection. If I call the Close() or Dispose() method on that SqlConnection object, it is returned to the connection pool.
然而,这并不真正告诉我if它真的关闭,或者如果我仍然有一个与数据库的活动连接。
However, that doesn't really tell me if it's really closed, or if I still have an active connection to the database.
如何强制SqlConnection在网络层关闭,或至少告诉它何时关闭?
How can I force a SqlConnection to close at the network level, or at least tell when it closes?
示例:
using(SqlConnection conn = new SqlConnection(DBConnString)) {
conn.Open();
SqlCommand cmd = conn.CreateCommand();
...
cmd.ExecuteReader(CommandBehavior.CloseConnection);
...
}
- :300 ms
- 第二次运行:100 ms
- 第三次运行:100 ms
- 时间(30分钟):300 ms
- First run: 300 ms
- Second run: 100 ms
- Third run: 100 ms
- After waiting a long time (30 minutes): 300 ms
- CommandBehavior.CloseConnection是否有效? (显然不是?)
- 在连接字符串中设置最大池大小= 0是否正常? (这将是一个pyrrhic解决方案)
- Dispose()是否工作?
- 文章连接池
- 这是另一个告诉我们关闭()不会真正关闭连接。
- 利弊连接池
- Article on Connection Pooling
- Here's another one that tells us that Close() doesn't really close the connection.
- An article on pros and cons connection pooling
如果连接为TRULY关闭,第二次和第三次运行也应为300 ms。但我知道连接并没有真正关闭这些运行(我检查了SQL Server的活动监视器)。
If the connection was TRULY closing, the second and third runs should also be 300 ms. But I know that the connection is not truly closed for those runs (I checked the SQL Server's activity monitor). It doesn't take the extra 200ms to perform authentication/etc.
如何强制连接真正关闭?
How do I force the connection to truly close?
想法
参考
ul>
推荐答案
这篇关于如何强制SqlConnection物理关闭,而使用连接池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!