这几天遇到的问题,就是发现,sqlconnection.open在数据库已经断开连接(如停掉sql service)时还能正常返回,没有错误发生,经过研究发现这是因为ado.net默认采取了连接池技术,当断开连接后,sqlconnection.open仍然可以从池中返回conn,但是已经是无效的,但是只有当你使用它的时候才会知道它是无效的,sqlconnection.open会到连接池中查看是否有对应的连接,有的话就拿出来,没有才会创建,当数据库断开后,在程序中调用sqlconnection.open会成功正是因为在连接池中仍然存在着对应的连接,但是已经是无效的了,这样使用时就会有异常,如调用DataAdapter.Fill方法,下面是一些相关资料:
SQL Server Best Practices Article
SQL Server Connection Pooling (ADO.NET)
http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx
Using Connection Pooling with SQL Server
- .NET Framework 4
- Visual Studio 2008
- .NET Framework 1.1
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