【发布时间】:2012-04-06 16:21:31
【问题描述】:
我以为我很聪明。但鉴于最近的发现,我不再那么确定了。在页面生命周期中,可能有任意数量的数据库交互。有的背靠背,有的散开。所以我发明了一个对象,它可以在 HttpContext.Items 字典中保持一个 SQL 连接的实例。然后每个 db 请求都使用此连接,当 http 请求结束时,我会正确处理连接。我们正在查看连接将在几百毫秒内打开,并且由于一些繁重的 http 缓存,可用连接用完不是问题。
关键是要防止由于建立新连接而产生额外的往返行程。但是当我偶然发现连接池的知识时,我认为它使保留 SqlConnection 的用处完全失效。还是这样?
场景 A 是否与场景 B 相同,性能方面?你会推荐哪个?场景 B 是否没有提供性能提升,甚至可能因为连接可能无法正确处理的某些极端情况而阻碍它?请原谅示例中的伪类,我不想用 barf 来混淆它们。
一个
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();
【问题讨论】: