我曾经认为自己很聪明。但是根据最近的发现,我不再那么确定了。在页面生命周期内,可能会有许多数据库交互。有些是连续的,有些则分散在各处。因此,我发明了一个对象,将SQL连接实例保持在HttpContext.Items字典中活动状态。每个数据库请求都使用该连接,并且当http请求结束时,我会正确地处理该连接。这个连接只需要打开几百毫秒的时间,在进行一些大量http缓存后,用尽可用连接的风险也不会很大。
重点是为了防止由于建立新连接而导致的额外往返。但当我了解到连接池的知识时,我觉得它基本上否定了保留SqlConnection的有用性。或者说呢?
对于性能而言,场景A和场景B是否相同?你会推荐哪个呢?场景B是否不提供性能增益,甚至可能因某些边缘情况未正确处理连接而阻碍性能?请原谅示例中的伪代码,我不想用肮脏的东西来弄乱它们。 B
重点是为了防止由于建立新连接而导致的额外往返。但当我了解到连接池的知识时,我觉得它基本上否定了保留SqlConnection的有用性。或者说呢?
对于性能而言,场景A和场景B是否相同?你会推荐哪个呢?场景B是否不提供性能增益,甚至可能因某些边缘情况未正确处理连接而阻碍性能?请原谅示例中的伪代码,我不想用肮脏的东西来弄乱它们。 B
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();