dbConn.Open inside using

367 Views Asked by At
using (IDbConnection dbConn = new System.Data.SqlClient.SqlConnection(ConnectionString))
{
    dbConn.Open();
    ...
    return result;
}
  1. Will the dbConn.Open() inside the using will use a different connection pool?
  2. If the question number 1 is true and if the code reaches the return, will this code leaves 2 open connection hanging?
2

There are 2 best solutions below

1
On

It will create a new connection which will then be disposed of when the using block has reached the end. It's a good idea to close you connection when you no longer need it, if you have more going on in the using block but the using block will handle that.

When the code reaches the return, it exits out of the using statement so it then does the disposing. It's not like it returns and doesn't finish in case thats what you are asking. The dispose is called as soon as the execution leaves that scope. Even if you get an exception the Dispose will be called.

A using block gets compiled into a try catch finally block and the finally is always executed and the finally contains the Dispose

0
On

Will the dbConn.Open() inside the using will use a different connection pool?

There is only one "connection pool".

If the question number 1 is true and if the code reaches the return, will this code leaves 2 open connection hanging?

Well question 1 is false, but here's what actually happens:

  • The code in the using statement creates the connection object.
  • When you call Open(), the connection object asks for an existing database connection from the pool, and creates one if the pool does not have one (perhaps the pool actually creates it, but that's an implementation detail)
  • When the block ends (or an exception is thrown), the using block goes out of scope and the connection object is disposed of, which closes and releases the database connection.

So there is only one connection object and one database connection. It is automatically disposed of when the using block goes out of scope (either by completing or my throwing an exception).