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

查看:131
本文介绍了如果我离开在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将处理所有的变量在我的网页,而且,连接对象了。但是,当它被设置,这是否被打开了previously自动关闭连接?我的意思是,当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文档是pretty的清楚这一点:

The MSDN documentation is pretty clear about this:

如果关闭SqlConnection超出   范围,也不会被关闭。因此,   你必须明确地关闭   通过调用连接关闭或   处置。关闭和处置的   功能上等同的。

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()它。该使用块是preferred。

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天全站免登陆