Close SqlConnection in the Finally when using “Using”

前端 未结 6 617
独厮守ぢ
独厮守ぢ 2020-12-21 00:06

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

6条回答
  •  一生所求
    2020-12-21 00:44

    You don't need to close conn in the finally block. The using block will handle closing the connection for you. (In fact, you probably don't need the try...finally at all in this case, unless you have other resources that need dealing with in the finally.)

    The using block will translate to something like this:

    var conn = new SqlConnection(/*...*/);
    try
    {
        // ...
    }
    finally
    {
        if (conn != null)
            ((IDisposable)conn).Dispose();
    }
    

    The Dispose method of the SqlConnection object will be called in the finally block, and the Dispose method goes on to call Close for you.

提交回复
热议问题