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

2023-09-04 22:33:29 作者:得不到的不必去乞討

我要关闭SqlConnection在最后,因为使用没有真正关闭和连接池已满。但我不知道什么是正确的方式来FO,由于美国康涅狄格州的对象是不可达的任何更多的在最后一节。

 尝试
{
    使用(VAR康恩=新的SqlConnection(_dbconnstr))
    {
        // ...
    }
}
赶上(例外前)
{
    // ...
}
最后
{
    conn.Close //?!?!?!?!???
}
 

解决方案

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

是expaded为:

 的SqlConnection康恩=新的SqlConnection(_dbconnstr);
尝试
{
    // code
}
最后
{
    conn.Dispose();
}
 
爱奇艺怎么关闭游戏消息通知 爱奇艺APP关闭游戏消息通知的方法

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

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.