[英]when does dispose method is called in using block
I am trying to test this piece of code by putting in breakpoints. 我试图通过输入断点来测试这段代码。 I want to make sure that after the using block the dispose method is called and the resources (SqlCommand), is gracefully released.
我想确保在使用块之后调用dispose方法并且优雅地释放资源(SqlCommand)。 However nowhere in the using block I hit any dispose?
然而在使用区块中我没有任何处置?
using (SqlCommand command = new SqlCommand(queryString, connection))
{
command.CommandType = CommandType.Text;
command.Parameters.Add("@OrganizationID", SqlDbType.Int);
command.Parameters["@OrganizationID"].Value = organizationId;
connection.Open();
SqlDataReader sqlDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
try
{
while (sqlDataReader.Read())
{
//do something
}
}
finally
{
sqlDataReader.Close();
}
}
The call to Dispose
of IDisposable
happens after the using
block has finished execution, normally or abnormally (ie through an exception). 在
using
块完成执行后,正常或异常(即通过异常)发生对Dispose
of IDisposable
的调用。
The only way you could catch the call in a source-level debugger is when you have the source code for your IDisposable
- in your case it would be the source code of SqlCommand
class. 在源代码级调试器中捕获调用的唯一方法是,当您拥有
IDisposable
的源代码时 - 在您的情况下,它将是SqlCommand
类的源代码。
One simple way of checking the way this works is to make your own IDisposable
implementation, put it into a using
block, and observe its behavior. 检查其工作方式的一种简单方法是创建自己的
IDisposable
实现,将其放入using
块,并观察其行为。 The call to Dispose
should follow immediately after completion of the using
block. 在完成
using
块之后,应立即调用Dispose
。
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.
using语句确保即使在对象上调用方法时发生异常,也会调用Dispose。 You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block;
您可以通过将对象放在try块中然后在finally块中调用Dispose来实现相同的结果; in fact, this is how the using statement is translated by the compiler.
实际上,这就是编译器如何翻译using语句。 The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):
前面的代码示例在编译时扩展为以下代码(注意额外的花括号以创建对象的有限范围):
Key part is the "achieve the same result by putting the object inside a try block and calling finally". 关键部分是“通过将对象放在try块中并最终调用来实现相同的结果”。
SqlCommand command = new SqlCommand(queryString, connection);
try {
// your code here
} finally {
command.Dispose();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.