到被使用LINQ是否有可能SQL连接泄漏?有可能、LINQ、SQL

2023-09-04 00:32:04 作者:- 宁死被窝不死书桌

我belived这是不可能得到的SQL连接泄漏使用LINQ的时候,却NumberOfReclaimedConnections的性能监视器跟踪显示大量和高负荷的,我们有时会像超时过期例外。超时时间已过获取从连接之前池。出现这种情况可能是因为所有池连接使用,最大池大小共识。

I belived it was not possible to get sql connection leaks when using LINQ, but perfmon tracing of NumberOfReclaimedConnections shows a high number and on high load we sometimes get exceptions like "Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached".

我们不会在datacontexts使用处置,sincewe二手DEFERED负荷。一些文章,博文告诉我,这不应该是一个问题。

We do not use Dispose on the datacontexts, sincewe used defered loading. Several articles and blogpost tells me that this should not be a problem.

不过,我们有时会这些异常。但不能说我们做保持连接打开每一个LINQ查询,那么我们将有更多的例外。

Still we gets these exceptions sometimes. But it can not be that every linq query we do keep the connection open, then we would have a lot more of the exceptions.

编辑

应用程序是一个WCF服务。

The application is a WCF service.

如果你看的LINQ的文档和大部分文章,他们声称的处置是没有必要释放连接。他们声称的DataContext只能保持连接打开了很短的时间就需要它。

If you look at the documentation of Linq and most of the articles, they claim that the Dispose is not necessary to release the connections. They claim that DataCOntext only keep the connection open for the short time it need it.

推荐答案

在你的的DataContext 未获处理,并保持活着,相关的连接将活路了。数据库连接的非托管资源和所有非托管资源,必须妥善处理。

When your DataContext is not disposed of and stays alive, the associated connection will stay alive too. Database connections are unmanaged resources and all unmanaged resources must be disposed of properly.

即使您使用延迟加载,并没有一个明确的范围,你还是应该清理数据库连接的工作逻辑单元的结束。在ASP.NET应用程序,最迟可能的时刻,这将是在请求处理的结束 - 在Globals.asax文件的Application_EndRequest方法。在一个WCF服务,任何有效的数据上下文应在每个服务方法调用结束处理。

Even if you use delay-loading and do not have a well-defined scope, you should still clean up database connections at the end of a logical unit of work. In ASP.NET apps, the latest possible moment for this would be at the end of request processing - in the Application_EndRequest method of the Globals.asax file. In a WCF service, any active data context should be disposed of at the end of every service method call.

的文档,这是模糊的,而大部分的时间,你可以逃脱不处理您的DataContext,也似乎的确有些场景从连接加载的数据保持连接本身活着。确认这是发生在你的情况下,最简单的方法就是测试它。

The documentation for this is vague and while most of the time, you can get away with not disposing your DataContext, there do appear to be some scenarios where the data loaded from a connection is keeping the connection itself alive. The easiest way to confirm that this is happening in your case is to test it.