且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在使用&QUOT关闭的SqlConnection在最后;使用"

更新时间:2023-01-12 20:05:31

 使用(VAR康恩=新的SqlConnection(_dbconnstr))
{
    // code
}
 

是expaded为:

 的SqlConnection康恩=新的SqlConnection(_dbconnstr);
尝试
{
    // code
}
最后
{
    conn.Dispose();
}
 

所以,你应该处理错误,但你可以忘记关闭连接。

I want to close the SqlConnection in the Finally since the using not really close it and the connection pool gets full. but I don't realize what's the right way to fo that since the conn object isn't reachable any more in the finally section.

try 
{
    using (var conn = new SqlConnection(_dbconnstr)) 
    {
        //...
    }
}
catch (Exception ex)
{
    //...
}
finally 
{
    conn.Close //?!?!?!?!???
}

using (var conn = new SqlConnection(_dbconnstr)) 
{
    //code
}

is expaded to:

SqlConnection conn = new SqlConnection(_dbconnstr);
try
{
    //code
}
finally
{
    conn.Dispose();
}

So you should handle errors but you can forget about closing connection.