0

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 Answers1

0

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.

Laurent LA RIZZA
  • 2,905
  • 1
  • 23
  • 41
  • It would be a MySqlCommand, however, what I am asking is **why** the using statement would be required in this specific example, not why it might be good coding practice. If I don't have the using statement for a MySqlCommand in this example, do I have a resource leak? – Steven Blair Jul 07 '15 at 13:37
  • The resource leak, were there one, would be inside the MySQL native API, a `MYSQL_RES` not `mysql_free_result`'d in this case. But it will be. `IDisposable` objects are generally written so that when the object is GC'd, undisposed resources are diposed of. – Laurent LA RIZZA Jul 07 '15 at 13:55