imba22
imba22

Reputation: 649

when does dispose method is called in using block

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();
    }
}

Upvotes: 2

Views: 4632

Answers (2)

dckuehn
dckuehn

Reputation: 2475

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):

Key part is the "achieve the same result by putting the object inside a try block and calling finally".

SqlCommand command = new SqlCommand(queryString, connection);
try {

      // your code here
} finally {

      command.Dispose();
}

From MSDN

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726929

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.

Upvotes: 6

Related Questions