Joh*_*ski 111 c# asp.net using sqlcommand sqlconnection
根据我在这里关于Disposable对象的另一个问题,我们应该在using块结束之前调用Close()吗?
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();
}
Run Code Online (Sandbox Code Playgroud)
CMS*_*CMS 106
由于您有一个使用块,因此将调用SQLCommand的Dispose方法并关闭连接:
// 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);
}
Run Code Online (Sandbox Code Playgroud)
sta*_*son 25
使用.NET Reflector反汇编SqlConnection :
protected override void Dispose(bool disposing)
{
if (disposing)
{
this._userConnectionOptions = null;
this._poolGroup = null;
this.Close();
}
this.DisposeMe(disposing);
base.Dispose(disposing);
}
Run Code Online (Sandbox Code Playgroud)
它在Dispose()中调用Close()
Tho*_*att 20
using关键字将正确关闭连接,因此不需要额外调用Close.
从有关SQL Server连接池的MSDN文章:
"我们强烈建议您在使用完毕后始终关闭连接,以便将连接返回到池中.您可以使用Connection对象的Close或Dispose方法,或打开一个内部的所有连接来执行此操作. 在C#中使用语句 "
使用.NET Reflector实际实现SqlConnection.Dispose 如下:
// 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);
}
Run Code Online (Sandbox Code Playgroud)
使用Reflector,你可以看到实际调用的Dispose方法;SqlConnectionClose()
protected override void Dispose(bool disposing)
{
if (disposing)
{
this._userConnectionOptions = null;
this._poolGroup = null;
this.Close();
}
this.DisposeMe(disposing);
base.Dispose(disposing);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36123 次 |
| 最近记录: |