我以为我很聪明.但鉴于最近的发现,我不再那么肯定了.在页面生命周期中,可以通过任意数量的数据库交互.一些背靠背,其他人分散开来.所以我发明了一个对象,它在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 ...
}
}
Run Code Online (Sandbox Code Playgroud)
乙
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();
Run Code Online (Sandbox Code Playgroud)
使用A部分中的代码.请让连接池完成它的工作.避免SqlConnection不惜一切代价保持静止.连接池是为此而设计的.
这是一篇MSDN文章供您参考.