简体   繁体   中英

C#.NET using block

I want to use the "using" block in my DAL layer. Like

using (SqlConnection con = new SqlConnection("connection string"))
{
     Command object
     Reader object
}

Since the SqlConnection object in initialised in the using block i know that this connection object will be automatically disposed when the control exits the using block scope.

But i am creating Command and Reader objects inside the using block. Do i have to explicitly close them or do i have to write another "using" block for them.

You should use using for the Command and Reader as well, or explicitly close them.

I normally code it like this:

var sql = "SELECT * FROM table";
using (var cn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, cn)) {
}

This limits the number of identations.

You typically write using-blocks for those as well, ie.

using (SqlConnection con = new SqlConnection("connection string"))
{
    con.Open();
    using (SqlCommand cmd = con.CreateCommand())
    {
        cmd.CommandText = "select * from table";
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            ...
        }
    }
}

It's worth writing a using block for any code that supports IDisposable interface. This way you ensure that you have done what you can to release any scarce resources.

You can make using blocks for any item that implements IDispose . So you can make nested using blocks for each of these, within the block for the connection, to ensure that they are properly disposed of after use.

You should use using() or finally blocks if you don't like using for your connections and readers. For readers, connection isn't closed until the reader is closed. Also I've read that using() doesn't 100% guarantee you that the connection will be closed but I don't know the reason behind that since it is converted to try - finally blocks and will be executed in any condition.

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