如果我在 ASP.NET 网页中保持数据库连接打开,会发生什么情况
假设我有一个 ASP.NET 页面。在页面加载事件处理程序中,我打开数据库连接并进行一些处理。但处理完成后,我没有通过调用连接对象的 CLOSE 方法显式关闭连接。
现在,当服务器端的页面处理完成时,GC 将处理我的页面中的所有变量,以及连接对象。但是当它被释放时,之前打开的连接是否会自动关闭?我的意思是,当GC处置连接对象时,是否会自动关闭与数据库服务器建立的连接?或者它只是简单地处理连接对象,并且数据库处的连接保持打开状态,直到数据库处发生连接超时,然后数据库服务器自行关闭连接?
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
MSDN 文档对此非常清楚:
使用
using
块自动处理它,或者显式地.Close()
它。using
块是首选。通过保持连接打开,您的应用程序最终可能会在尝试新请求时耗尽连接,从而导致错误。我在调试应用程序时遇到了这样的问题。最初的开发人员未能在几个页面上显式关闭连接,并且流量足够高,以至于用户开始收到错误。我将有问题的连接包装在
using
块中,问题就消失了。The MSDN documentation is pretty clear about this:
Either use the
using
blocks to have it disposed automatically, or explicitly.Close()
it. Theusing
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.连接保持打开状态。如果您有大量综合浏览量和大量打开的连接,则可能会收到 500 错误。
Connection is remained open. If you have lots of pageviews, and lots open connections, you can get 500 error.
在页面对象最终确定之后(而不是当)之前,您的连接不会关闭,这可能需要一段时间。很容易达到最大可用连接数并开始出现错误。
Your connections won't be closed until after (not when) your page object is finalized, and that might be a while. It would be very easy to max out the number of available connections and start getting errors.
你应该使用
using
块,那么你就不必问这个问题:You should use
using
blocks, then you won't have to ask the question:除非 GC 选择,否则您的连接不会关闭,如果您有很多访客导致大量连接,那么这可能会很糟糕。此外,如果您尝试打开一个打开的连接,它会抛出错误,因此您必须检查更好的方法是将其写入 using 块或自己关闭连接。
your connection won't be closed unless chosen by GC and if you have many visitors resulting in lots of connections then this may be horrible. Also if you try to open an opened connection it will throw error so you have to check for that better is either write it in using block or close the connection yourself.