If an SqlCommand is executed and times out, is the respective SqlConnection closed and/or disposed?

StackOverflow https://stackoverflow.com/questions/1840358

  •  12-09-2019
  •  | 
  •  

Question

If an SqlCommand is executed and times out, is the respective SqlConnection closed and/or disposed?

Was it helpful?

Solution

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.
}

OTHER TIPS

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(...))
{
    // ...  
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top