简体   繁体   中英

DBCommand using block

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM