Using Statement and Connection Pooling

北城以北 提交于 2019-12-11 07:11:55

问题


I recently came to know the concept of 'connection pooling' in .NET, and as such I have a little doubt I would like anyone to clarify it for me. If I use the following piece of code, when will the database connection be returned to the pool so that it can be used by another part of the application?

using (SqlConnection NewConnection = new SqlConnection(ConnectionString))
{
    using (SqlCommand NewCommand = new SqlCommand("SomeCommand", NewConnection))
    {
        try
        {
            NewConnection.Open();

            // Do some work...

            NewConnection.Close(); // <-- Here?
        }
        catch
        {
            // Error handling...
        }
    }
}

// <-- Here?

Thank you very much.


回答1:


The connection will indeed be returned to the pool after the using block has finished executing.

The using statement is syntactic sugar - the compiler generates a correct Dispose block which closes the connection, thus returning it to the connection pool.




回答2:


You need to consider the SqlConnection object and the underlying connection as separate. It is the underlying connection that is pooled. This is returned to the pool when the SqlConnection is disposed, either by explicit usage of Dispose(), or by a using block*. Later, a new (different) SqlConnection might be created with the same underlying connection.

So: the magic happens:

using (SqlCommand NewCommand = new SqlCommand("SomeCommand", NewConnection))
{
    ...
} <==== here

*=it might also (I didn't check) be released back to the pool by GC/finalizer - but we shouldn't focus on that because if that happens you're already doing it wrong.



来源:https://stackoverflow.com/questions/6251733/using-statement-and-connection-pooling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!