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

后端 未结 6 849
攒了一身酷
攒了一身酷 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:31

    From MSDN (DataContext Constructor (IDbConnection)):

    If you provide an open connection, the DataContext will not close it. Therefore, do not instantiate a DataContext with an open connection unless you have a good reason to do this.

    So basically, it looks like your connections are waiting for GC to finalize them before they will be released. If you have lots of code that does this, one approach might be to overide Dispose() in the data-context's partial class, and close the connection - just be sure to document that the data-context assumes ownership of the connection!

        protected override void Dispose(bool disposing)
        {
            if(disposing && this.Connection != null && this.Connection.State == ConnectionState.Open)
            {
                this.Connection.Close();
                this.Connection.Dispose();
            }
            base.Dispose(disposing);
        }
    

    Personally, I would happily give it (regular data-context, w/o the hack above) an open connection as long as I was "using" the connection (allowing me to perform multiple operations) - i.e.

    using(var conn = GetConnection())
    {
       // snip: some stuff involving conn
    
       using(var ctx = new FooContext(conn))
       {
           // snip: some stuff involving ctx
       }
    
       // snip: some more stuff involving conn
    }
    

提交回复
热议问题