views:

194

answers:

3

If an sqlcommand is executed and times-out, is the respective sqlconnection closed and/or disposed?

Thanks in advance!

+5  A: 

No, you still need to clean up after yourself. Using a using block will cause it to be disposed though:

using (SqlConnection connection = new SqlConnection(...))
{
    // ...  
}
md5sum
So it is not even closed?
Clean
No it isn't. (why do I need to have 15 characters!)
JonH
I'm not 100% sure on that, but calling `SqlConnection.Dispose()` also invokes `SqlConnection.Close()`. So the using block is 100% effective.
md5sum
+1 for the standard example
Arthur
+6  A: 

Unless you have your SqlConnection wrapping in a using statement, you're still responsible for closing and disposing the connection (just like any other exception).

You could also use a try/catch/finally block:

try
{
    // Create and execute your SqlCommand here
}
catch(SqlException ex)
{
    // Catch the timeout
}
finally
{
    // Close and Dispose the SqlConnection you're using
}

But using is much cleaner and disposes automatically:

using(SqlConnection conn = new SqlConnection())
{
    // Do your work here.
    // The SqlConnection will be closed and disposed at the end of the block.
}
Justin Niessner
A: 

This should all be wrapped around a finally clause after the exception so that you are closing your connection and cleaning up any sql realated object resource. Look at try / catch / finally and put the clean up code in your finally statement.

JonH