.net SqlConnection not being closed even when within a using { }

后端 未结 6 839
攒了一身酷
攒了一身酷 2021-02-13 02:06

Please help!

Background info

I have a WPF application which accesses a SQL Server 2005 database. The database is running locally on the machine the appl

6条回答
  •  逝去的感伤
    2021-02-13 02:10

    I experienced the same issue using the Entity Framework. My ObjectContext was wrapped around a using block.

    A connection was established when I called SaveChanges(), but after the using statement was out of scope, I noticed that SQL Management Studio still had a "AWAITING COMMAND" for the .NET SQL Client. It looks like this has to do with the behavior of the ADO.NET provider which has connection pooling turned on by default.

    From "Using Connection Pooling with SQL Server" on MSDN (emphasis mine):

    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.

    Also ClearAllPools and ClearPool seems useful to explicitly close all pooled connections if needed.

提交回复
热议问题