我以为我很聪明。但鉴于最近的发现,我不再那么肯定。在页面生命周期中,可以通过任意数量的数据库交互。一些背靠背,另一些分散开来。所以我发明了一个对象,它在HttpContext.Items字典中保持一个SQL连接的实例。每个数据库请求然后使用这个连接,并且当http请求结束时,我正确地处理连接。我们正在研究几百毫秒的连接将会打开,并且有一些重大的http缓存,用完的连接不再是一个问题。SqlConnection和Pool,保持开放连接kung-foo或foo-bar?
点是为了防止额外的往返由于新连接的建立。但是当我偶然发现连接池的知识时,我认为它很大程度上使保留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 ...
}
}
乙
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();
同意 - SQL服务器具有内置的连接池机制(可以调整以适应您的规模),所以不要担心打开连接只是让池做魔术 – 2012-04-06 16:27:51
这就是我最近的想法。感谢您验证它。 – Levitikon 2012-04-06 16:41:03
我希望MSDN能够更新ADO.NET池化文章,并详细说明这一点。我很多时候都不得不争论这一点。让游泳池做好工作! – mafue 2012-05-15 18:12:35