简体   繁体   中英

Freeing connections and commands with using

When both a SqlConnection and a SqlCommand are created in a single using block, are both freed on exit, or are nested using blocks necessary?

using (SqlCommand command = new SqlConnection(ConnectionString).CreateCommand()) {

    // Use command..
}

A using block just calls .Dispose() on the resource that you declare once the block is finished executing.

MSDN: The Using Statement

So, yes, you should wrap both the SqlConnection and SqlCommand in a using statement to ensure that both of these resources are properly disposed.

EDIT: You can also stack using commands like so:

using (SqlConnection connection = new SqlConnection("connection string"))
    using (SqlCommand command = new SqlCommand("command", connection)) {
       // Your code here
}

The most important part is disposing the SqlConnection object, with the help of the using statement preferably. So following your example, this would be the appropriate way of doing that:

using (var cn = new SqlConnection(ConnectionString))
{
    cn.Open();

    using (var command = cn.CreateCommand())
    {
        // Use command..
    }
}

Behind the scenes this is what the using statement translates into, you can appreciate how it helps to reduce boilerplate:

{
    var cn = new SqlConnection(ConnectionString);

    try
    {
        cn.Open();

        {
            var command = cn.CreateCommand();

            try
            {
                // Use command..
            }
            finally
            {
                command.Dispose();
            }
        }
    }
    finally
    {
        cn.Dispose();
    }
}

By disposing the SqlConnection instance with the using statement you can be sure that the connection will be closed after leaving the scope, even if an exception occurs.

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