如何在使用连接池时强制 SqlConnection 物理关闭?

How to force a SqlConnection to physically close, while using connection pooling?(如何在使用连接池时强制 SqlConnection 物理关闭?)
本文介绍了如何在使用连接池时强制 SqlConnection 物理关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

However, that doesn't really tell me if it's really closed, or if I still have an active connection to the database.

How can I force a SqlConnection to close at the network level, or at least tell when it closes?

Example:

using(SqlConnection conn = new SqlConnection(DBConnString)) {

   conn.Open();
   SqlCommand cmd = conn.CreateCommand();
   ...
   cmd.ExecuteReader(CommandBehavior.CloseConnection);
   ...
}

  • First run: 300 ms
  • Second run: 100 ms
  • Third run: 100 ms
  • After waiting a long time (30 minutes): 300 ms

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?

Ideas

  • Does CommandBehavior.CloseConnection work? (apparently not?)
  • Does setting "Max Pool Size = 0" in the connection string work? (this would be a pyrrhic solution)
  • Does Dispose() work?

References

  • 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

解决方案

Maybe SqlConnection.ClearPool ?

这篇关于如何在使用连接池时强制 SqlConnection 物理关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)