C#.NET using block

做~自己de王妃 提交于 2019-12-06 01:10:35

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!