我曾以为我很聪明。但鉴于最近的发现,我不再那么确定了。在页面生命周期中,可能有任意数量的数据库交互。有的背靠背,有的散开。所以我发明了一个对象,它在 HttpContext.Items 字典中保持一个 SQL 连接的实例处于事件状态。然后每个 db 请求都使用此连接,当 http 请求结束时,我会正确处理该连接。我们看到连接将打开几百毫秒,并且使用一些繁重的 http 缓存,可用连接用完不是问题。
关键是要防止由于建立新连接而导致额外的往返。但是当我偶然发现连接池的知识时,我认为它使保留 SqlConnection 的用处完全无效。或者是吗?
在性能方面,场景 A 与场景 B 是否相同?你会推荐哪个?方案 B 是否没有提供性能提升,甚至可能会因为连接可能未正确处理的某些边缘情况而阻碍性能提升?请原谅示例中的伪性,我不想用 barf 把它们弄乱。
A
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("...", connection))
{
... doing database stuff ...
}
}
... traversing the stack ...
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("...", connection))
{
... doing database stuff ...
}
}
B
var connectionKeeper = new ConnectionKeeper();
// Add to the context items so it can be used anywhere
Context.Items.Add("Connection", connectionKeeper);
... traversing the stack ...
using (var command = new SqlCommand("...", connectionKeeper.Connection))
{
... doing database stuff
}
... traversing the stack ...
using (var command = new SqlCommand("...", connectionKeeper.Connection))
{
... doing database stuff
}
... traversing the stack ...
// The end of the request
sqlKeeper.Dispose();
最佳答案
使用 A 部分中的代码。请让连接池完成它的工作。不惜一切代价避免保留静态 SqlConnection
。连接池就是为此而设计的。
这里有一篇 MSDN 文章供您引用。
SQL Server Connection Pooling (ADO.NET)
关于c# - SqlConnection 和 Pool,是保持开放连接 kung-foo 还是 foo-bar?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10046214/