简体   繁体   English

C#.NET使用块

[英]C#.NET using block

I want to use the "using" block in my DAL layer. 我想在DAL层中使用“using”块。 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. 由于在使用块中初始化的SqlConnection对象,我知道当控件退出使用块作用域时,将自动处理此连接对象。

But i am creating Command and Reader objects inside the using block. 但我在使用块内创建Command和Reader对象。 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. 您应该使用using命令和读者一样好,甚至明确地关闭它们。

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. 值得为任何支持IDisposable接口的代码编写一个using块。 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 . 您可以为实现IDispose任何项目using块。 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. 因此,您可以在连接块内为每个嵌套using块,以确保在使用后对它们进行适当处理。

You should use using() or finally blocks if you don't like using for your connections and readers. 如果您不喜欢使用连接和读者,则应使用using()finally块。 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. 另外我已经读过, using()并不是100%保证连接将被关闭但我不知道背后的原因,因为它被转换为try - finally块并且将在任何条件下执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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