小编典典

SqlConnection和Pool是否保持打开的连接kung-foo或foo-bar?

sql

我以为我很聪明。但是鉴于最近的发现,我不确定。在页面生命周期中,可能有许多数据库交互。有些背靠背,有些则散布开来。因此,我发明了一个对象,该对象在HttpContext.Items字典中使SQL连接的实例保持活动状态。然后,每个数据库请求都使用此连接,并且当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 ...
   }
}

   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();

阅读 255

收藏
2021-04-22

共1个答案

小编典典

使用A部分中的代码。请让连接池完成它的工作。避免SqlConnection不惜一切代价保持静态。连接池是为此目的而设计的。

这是MSDN文章,供您参考。

SQL Server连接池(ADO.NET)

2021-04-22