C# 在使用块或在使用块声明时声明IDisposable成员有什么区别?
我的代码如下:C# 在使用块或在使用块声明时声明IDisposable成员有什么区别?,c#,dispose,using-statement,C#,Dispose,Using Statement,我的代码如下: using (SqlCommand command = new SqlCommand()) { command.CommandType = System.Data.CommandType.StoredProcedure; command.Connection = new SqlConnection(); command.CommandText = ""; command.Parameters.Ad
using (SqlCommand command = new SqlCommand())
{
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Connection = new SqlConnection();
command.CommandText = "";
command.Parameters.Add(new SqlParameter("@ExperienceLevel", 3).Direction = System.Data.ParameterDirection.Input);
SqlDataReader dataReader = command.ExecuteReader();
}
在声明SqlConnection时是否有任何功能上的影响,我目前正在声明它,而不是像这样声明它
using (SqlCommand command = new SqlCommand())
using (SqlConnection connection = new SqlConnection())
谢谢是的,下面的代码将正确处理SqlConnection,而上面的代码不会。使用
块(内部实现为try
…finally
)的确保无论您如何退出块,对象都将被释放。是的,存在差异。处置SqlCommand
不会自动处置与其关联的SqlConnection
。您可以通过这种方式泄漏连接,这将干扰ADO.NET连接池;如果在代码运行时查看数据库服务器的活动,您将看到新的连接正在打开,而不是关闭
您应该始终使用第二个版本。实际上,SqlConnection
对象是您真正需要处理的对象。您应该始终尽可能快地处置实现了IDisposable
的任何东西,但未能处置SqlConnection
尤其危险。是的,最好使用2个使用块,每个资源1个
在这种情况下,您可以只使用1,但它应该围绕连接,而不是围绕命令
但你真的不想知道或关心这些细节。如果类实现IDispsoable接口,则在using(){}
块中使用其实例,除非有特殊原因不这样做 我使用以下模式:
using(var connection = new SqlConnection("ConnectionName"))
using(var command = new SqlCommand())
{
command.Connection = connection;
// setup command
var reader = command.ExecuteReader();
// read from the reader
reader.Close();
}