根据我的另一个question here about Disposable objects,我们应该在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();
}
发布于 2009-07-28 18:26:17
由于您有一个using块,因此将调用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);
}
发布于 2009-07-28 18:28:07
使用.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);
}
它在Dispose()内部调用Close()
发布于 2009-07-28 18:29:59
使用Reflector,您可以看到SqlConnection
的Dispose
方法实际上调用了Close()
;
protected override void Dispose(bool disposing)
{
if (disposing)
{
this._userConnectionOptions = null;
this._poolGroup = null;
this.Close();
}
this.DisposeMe(disposing);
base.Dispose(disposing);
}
https://stackoverflow.com/questions/1195829
复制相似问题