ADO.NET SqlData 客户端连接永远不会消失

发布于 2024-08-05 03:18:24 字数 189 浏览 1 评论 0原文

我正在开发的一个 ASP.NET 应用程序可能有几百个用户尝试连接。我们收到一条错误消息,表明已达到池中的最大连接数。我了解 ADO.NET 中连接池的概念,尽管在测试中我发现连接在建立连接并关闭浏览器几天后在 ms sql 2005 服务器上保持“睡眠”状态。我尝试限制连接字符串中的连接生存期,但这没有效果。我应该推送最大连接数吗?我是否完全误判了真正的问题?

An asp.net application I am working on may have a couple hundred users trying to connect. We get an error that the maximum number of connections in the pool has been reached. I understand the concept of connection pools in ADO.NET although in testing I've found that a connection is left "sleeping" on the ms sql 2005 server days after the connection was made and the browser was then closed. I have tried to limit the connection lifetime in the connection string but this has no effect. Should I push the max number of connections? Have I completely misdiagnosed the real problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

素手挽清风 2024-08-12 03:18:24

所有数据库连接都必须包装在 try...finally 中:

SqlConnection myConnection = new SqlConnection(connString);
myConnection.Open();
try
{
}
finally
{
   myConnection.Close();
}

或者...更好的是,创建一个 DAL(数据访问层),在其 Dispose 方法中调用 Close() 并包装所有数据库使用 using 进行调用:

using (MyQueryClass myQueryClass = new MyQueryClass())
{
   // DB Stuff here...
}

一些注意事项:ASP.NET 确实依赖于您来释放连接。在它们超出范围后,它通过GC释放它们,但是您不能指望这种行为,因为它可能需要很长时间才能生效 -比您在连接池耗尽之前所能承受的时间要长得多。说到这里 - ASP.NET 实际上会在您请求时将您的连接集中到数据库(回收旧连接,而不是完全释放它们,然后从数据库重新请求它们)。就您而言,这并不重要:您仍然必须调用 Close()!

此外,您可以使用连接字符串(例如最小/最大池大小等)来控制池。有关详细信息,请参阅 MSDN 上的本文

All of your database connections must either be wrapped in a try...finally:

SqlConnection myConnection = new SqlConnection(connString);
myConnection.Open();
try
{
}
finally
{
   myConnection.Close();
}

Or...much better yet, create a DAL (Data Access Layer) that has the Close() call in its Dispose method and wrap all of your DB calls with a using:

using (MyQueryClass myQueryClass = new MyQueryClass())
{
   // DB Stuff here...
}

A few notes: ASP.NET does rely on you to release your Connections. It will release them through GC after they've gone out of scope but you can not count on this behavior as it may take a very long time for this to kick in - much longer than you may be able to afford before your connection pool runs out. Speaking of which - ASP.NET actually pools your connections to the database as you request them (recycling old connections rather than releasing them completely and then requesting them anew from the database). This doesn't really matter as far as you are concerned: you still must call Close()!

Also, you can control the pooling by using your connection string (e.g. Min/Max pool size, etc.). See this article on MSDN for more information.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文