SqlConnection.Open在数据库断开时仍可以正常返回

本文探讨了当数据库断开时,SqlConnection.Open为何仍能返回,揭示了ADO.NET的连接池机制。即使数据库服务停止,打开连接可能从池中获取已关闭但未释放的连接,导致在使用时才暴露出问题。了解这一行为有助于优化应用程序的性能和错误处理。
摘要由CSDN通过智能技术生成

这几天遇到的问题,就是发现,sqlconnection.open在数据库已经断开连接(如停掉sql service)时还能正常返回,没有错误发生,经过研究发现这是因为ado.net默认采取了连接池技术,当断开连接后,sqlconnection.open仍然可以从池中返回conn,但是已经是无效的,但是只有当你使用它的时候才会知道它是无效的

 

一些相关资料:

 

SQL Server Connection Pooling (ADO.NET)
http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx

 

Using Connection Pooling with SQL Server 

 

Connecting to a database server typically consists of several time-consuming steps. A physical channel such as a socket or a named pipe must be established, the initial handshake with the server must occur, the connection string information must be parsed, the connection must be authenticated by the server, checks must be run for enlisting in the current transaction, and so on.

In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling .

Connection pooling reduces the number of times that new connections need to be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks to see if there is an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of actually closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

Only connections with the same configuration can be pooled. ADO.NET keeps several pools concurrently, one for each configuration. Connections are separated into pools by connection string, as well as by Windows identity when integrated security is used.

Pooling connections can significantly enhance the performance and scalability of your application. Connection pooling is enabled by default in ADO.NET. Unless you explicitly disable it, the pooler will optimize the connections as they are opened and closed in your application. You can also supply several connection string modifiers to control connection pooling behavior. For more information, see "Controlling Connection Pooling with Connection String Keywords" later in this topic.

Pool Creation and Assignment

When a connection is first opened, a connection poo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值