C#.NET using block

柔情痞子 提交于 2019-12-07 18:00:27

问题


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.


回答1:


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.




回答2:


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())
        {
            ...
        }
    }
}



回答3:


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.




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/4487743/c-net-using-block

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