I am trying to test this piece of code by putting in breakpoints. I want to make sure that after the using block the dispose method is called and the resources (SqlCommand), is gracefully released. However nowhere in the using block I hit any dispose?
using (SqlCommand command = new SqlCommand(queryString, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("@OrganizationID", SqlDbType.Int);
command.Parameters["@OrganizationID"].Value = organizationId;
connection.Open();
SqlDataReader sqlDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
try
{
while (sqlDataReader.Read())
{
//do something
}
}
finally
{
sqlDataReader.Close();
}
}
The call to Dispose of IDisposable happens after the using block has finished execution, normally or abnormally (i.e. through an exception).
The only way you could catch the call in a source-level debugger is when you have the source code for your IDisposable - in your case it would be the source code of SqlCommand class.
One simple way of checking the way this works is to make your own IDisposable implementation, put it into a using block, and observe its behavior. The call to Dispose should follow immediately after completion of the using block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With