[ACCEPTED]-Close SqlConnection in the Finally when using "Using-sql
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 1 but you can forget about closing connection.
You don't need to close conn
in the finally
block. The 8 using
block will handle closing the connection 7 for you. (In fact, you probably don't need 6 the try...finally
at all in this case, unless you have 5 other resources that need dealing with in 4 the finally
.)
The using
block will translate to something 3 like this:
var conn = new SqlConnection(/*...*/);
try
{
// ...
}
finally
{
if (conn != null)
((IDisposable)conn).Dispose();
}
The Dispose
method of the SqlConnection
object will 2 be called in the finally
block, and the Dispose
method 1 goes on to call Close
for you.
Exiting a using block calls .Dispose()
on the object, for 2 a SqlConnection
will close the connection and any open 1 resources.
So the try
, finally
block is not needed.
AFAIK, the following using statement:
using (var conn = new SqlConnection(_dbconnstr))
{
}
Is 1 equivalent to:
SqlConnection conn;
try
{
//`using` scope operations are executed here
conn = new SqlConnection(_dbconnstr));
}
catch
{
//exceptions are bubbled
throw;
}
finally
{
//Dispose is always called
conn.Dispose();
}
As per my understanding Dispose() method 2 of connection object will close the Connection. You 1 don't need to call Connection.Close explicitly.
The way you are closing the connection with 2 Using
is Ok. Perhaps you might have forgotten 1 to close some DataReaders instead ?
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.