如果我在ASP.NET网页中打开数据库连接,会发生什么 [英] What happens if I leave a database connection open in an ASP.NET web page

查看:143
本文介绍了如果我在ASP.NET网页中打开数据库连接,会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个ASP.NET页面。在页面加载事件处理程序中,我打开一个数据库连接并做一些处理。但是在处理完成后,我不通过调用连接对象的CLOSE方法显式地关闭连接。

Suppose that I have an ASP.NET page. In the page load event handler, I open a database connection and do some processing. But after the processing is done, I don't close the connection explicitly by calling the CLOSE method of the connection object.

现在当服务器端的页面处理是完成后,GC会将所有的变量放在我的页面中,还有连接对象。但是当它被处理时,先前打开的连接是否自动关闭?我的意思是,当GC放置连接对象时,它是否自动关闭与数据库服务器建立的连接;或者它只是处理连接对象,并且数据库处的连接保持打开,直到数据库发生连接超时,然后数据库服务器自己关闭连接。

Now when the page processing at the server side is finished, the GC will dispose all the variables in my page, and also, the connection object too. But when it is disposed, does the connection that was opened previously is automatically closed? I mean, when GC disposes the connection object, does it automatically close the connection that was established with the database server; or it simply dispose the connection object, and the connection at the database is remained open, until the connection timeout occurs at the database and then the database server closes the connection by itself?

推荐答案

MSDN文档对此很清楚:


如果SqlConnection超出
范围,关闭。因此,
必须通过调用Close或
Dispose来显式关闭
连接。关闭和处理是
功能等价的。

If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent.

使用使用块自动处理,或者显式地 .Close()使用块是首选。

Either use the using blocks to have it disposed automatically, or explicitly .Close() it. The using blocks are preferred.

通过保持连接打开您的应用程序可能最终耗尽连接,尝试,导致错误。我在调试的应用程序中遇到了这样的问题。原始开发人员无法在几个页面上显式关闭连接,流量高到足以让用户开始收到错误。我在中使用块封装了违规的连接,问题消失了。

By leaving connections open your application may eventually run out of connections when new requests are attempted, resulting in errors. I've faced such a problem in an application I was debugging. The original developers failed to close the connections explicitly on a few pages and traffic was high enough that users started getting errors. I wrapped the offending connections in a using block and the problem went away.

这篇关于如果我在ASP.NET网页中打开数据库连接,会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆