我是否必须在 SQLConnection 被释放之前关闭它?
根据我的另一个问题关于一次性对象,我们应该在 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();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
由于您有一个 using 块,因此将调用 SQLCommand 的 Dispose 方法并关闭连接:
Since you have a using block, the Dispose method of the SQLCommand will be called and it will close the connection:
使用 .NET Reflector 反汇编 SqlConnection:
它在 Dispose( 内部调用 Close() )
Disassembly of SqlConnection from using .NET Reflector:
It calls Close() inside of Dispose()
using 关键字将正确关闭连接,因此不需要额外调用 Close。
来自关于 SQL Server 连接池的 MSDN 文章:
使用.NET Reflector实际实现SqlConnection.Dispose如下:
The using keyword will close the connection correctly so the extra call to Close is not required.
From the MSDN article on SQL Server Connection Pooling:
The actual implementation of SqlConnection.Dispose using .NET Reflector is as follows:
使用Reflector,可以看到
Dispose
方法SqlConnection
实际上确实调用了Close()
;Using Reflector, you can see that the
Dispose
method ofSqlConnection
actually does callClose()
;不,在 SqlConnection 上调用 Dispose() 也会调用 Close()。
MSDN - SqlConnection.Dispose()
No, calling Dispose() on SqlConnection also calls Close().
MSDN - SqlConnection.Dispose()
不,无论如何,Using 块都会为您调用
Dispose()
,因此无需调用Close()
。No, having the Using block calls
Dispose()
for you anyway, so there is no need to callClose()
.不,在调用 Dispose 之前没有必要关闭连接。
某些对象(如 SQLConnections)可以在调用 Close 后重新使用,但在调用 Dispose 后则不能重新使用。 对于其他对象,调用 Close 与调用 Dispose 相同。 (我认为ManualResetEvent和Streams的行为是这样的)
No, it is not necessary to Close a connection before calling Dispose.
Some objects, (like SQLConnections) can be re-used afer calling Close, but not after calling Dispose. For other objects calling Close is the same as calling Dispose. (ManualResetEvent and Streams I think behave like this)
不会,SqlConnection类继承自IDisposable,当遇到使用结束(对于连接对象)时,它会自动调用SqlConnection类上的Dispose。
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.