DBCommand using block

733 Views Asked by At

I have the following code:

using (MySqlConnection conn = new MySqlConnection(connStr))
{
    conn.Open();

    cmd = conn.CreateCommand();
    cmd.CommandText = "SELECT * FROM Events";
    cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();
}

From reading a few articles on this site, it is suggested that the DbCommand should be in a using block, however, I can't see why this is needed. The Connection is closed, so what is DbCommand holding on to that requires a using block? Is it really the case if a class inherits from IDisposable that you must use a using block or manually called Dispose?

I ran a simulator with 100 threads on the code above, and also with code with a using block on the DbCommand and I could see no real differences in memory usage.

1

There are 1 best solutions below

2
Laurent LA RIZZA On

DbCommand is abstract, and does not presuppose what native resources the vendor-specific subclass will hold, and in what order they should be released. Proper nesting of using blocks seems a reasonable implicit coding convention.