EF DBContext dispose not closing the connection

前端 未结 1 1651
鱼传尺愫
鱼传尺愫 2020-12-11 15:15

I am using the EF 6.1.0

I have below custom DBContex object as DBEntites

public partial class DbEntities : DbContext
{
    public DbEntities()
              


        
相关标签:
1条回答
  • 2020-12-11 16:01

    As was figured out in comments, the reason is indeed connection pooling performed by .NET. .NET maintains a pool of connections for every connection string you use in your application, for perfomance reasons (because opening and closing connections often might be costly in terms of perfomance). That pool has certain minimum and maximum size (controlled by MinPoolSize and MaxPoolSize connection string parameters). When you open a connection (via SqlConnection.Open) - it might be taken out of the pool and not really opened afresh. When you close connection (which is also done by disposing EF context) - connection might be put into the pool instead, and not really closed. When connection is idle for certain time (about 5 minutes) - it might be removed from the pool.

    If you (for some reason) want to avoid that, you can either set MaxPoolSize to 0 for your connection string, or clear pool explicitly by SqlConnection.ClearPool or SqlConnection.ClearAllPools.

    0 讨论(0)
提交回复
热议问题