是否可以使用 LINQ 获取 sql 连接泄漏?

时间:2023-03-08
本文介绍了是否可以使用 LINQ 获取 sql 连接泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信在使用 LINQ 时不可能出现 sql 连接泄漏,但是 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".

我们不在数据上下文上使用 Dispose,因为我们使用了延迟加载.几篇文章和博文告诉我这应该不是问题.

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 的文档和大多数文章,他们声称 Dispose 不是释放连接所必需的.他们声称 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.

这篇关于是否可以使用 LINQ 获取 sql 连接泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:在 Linq to SQL 中按年中的周(周数)分组 下一篇:当 ios 7 虚拟键盘存在时,Div 元素不会停留在底部

相关文章

最新文章