Do I have to Close() a SQLConnection before it get

2019-01-10 21:35发布

Per my other question here about Disposable objects, should we call Close() before the end of a using block?

using (SqlConnection connection = new SqlConnection())
using (SqlCommand command = new SqlCommand())
{
    command.CommandText = "INSERT INTO YourMom (Amount) VALUES (1)";
    command.CommandType = System.Data.CommandType.Text;

    connection.Open();
    command.ExecuteNonQuery();

    // Is this call necessary?
    connection.Close();
}

8条回答
对你真心纯属浪费
2楼-- · 2019-01-10 22:12

Since you have a using block, the Dispose method of the SQLCommand will be called and it will close the connection:

// System.Data.SqlClient.SqlConnection.Dispose disassemble
protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close();
    }
    this.DisposeMe(disposing);
    base.Dispose(disposing);
}
查看更多
乱世女痞
3楼-- · 2019-01-10 22:14

No, having the Using block calls Dispose() for you anyway, so there is no need to call Close().

查看更多
看我几分像从前
4楼-- · 2019-01-10 22:17

Using Reflector, you can see that the Dispose method of SqlConnection actually does call Close();

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close();
    }
    this.DisposeMe(disposing);
    base.Dispose(disposing);
}
查看更多
对你真心纯属浪费
5楼-- · 2019-01-10 22:20

No, the SqlConnection class inherits from IDisposable, and when the end of using (for the connection object) is encountered, it automatically calls the Dispose on the SqlConnection class.

查看更多
我想做一个坏孩纸
6楼-- · 2019-01-10 22:25

No, calling Dispose() on SqlConnection also calls Close().

MSDN - SqlConnection.Dispose()

查看更多
Lonely孤独者°
7楼-- · 2019-01-10 22:33

Disassembly of SqlConnection from using .NET Reflector:

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close();
    }

    this.DisposeMe(disposing);
    base.Dispose(disposing);
}

It calls Close() inside of Dispose()

查看更多
登录 后发表回答