当 using 语句中抛出异常时,Dispose 是否仍会被调用?
在下面的示例中,如果在 using
语句中抛出异常,连接是否会关闭并释放?
using (var conn = new SqlConnection("..."))
{
conn.Open();
// stuff happens here and exception is thrown...
}
我知道下面的代码将确保它确实如此,但我很好奇 using 语句是如何做到这一点的。
var conn;
try
{
conn = new SqlConnection("...");
conn.Open();
// stuff happens here and exception is thrown...
}
// catch it or let it bubble up
finally
{
conn.Dispose();
}
有关的:
What is the proper way to ensure a SQL connection is closed when an exception is thrown?In the example below, is the connection going to close and disposed when an exception is thrown if it is within a using
statement?
using (var conn = new SqlConnection("..."))
{
conn.Open();
// stuff happens here and exception is thrown...
}
I know this code below will make sure that it does, but I'm curious how using statement does it.
var conn;
try
{
conn = new SqlConnection("...");
conn.Open();
// stuff happens here and exception is thrown...
}
// catch it or let it bubble up
finally
{
conn.Dispose();
}
Related:
What is the proper way to ensure a SQL connection is closed when an exception is thrown?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,
using
将代码包装在 try/finally 块中,其中finally
部分将调用Dispose()
(如果存在)。 但是,它不会直接调用Close()
,因为它只检查正在实现的IDisposable
接口,从而检查Dispose()
方法。另请参阅:
Yes,
using
wraps your code in a try/finally block where thefinally
portion will callDispose()
if it exists. It won't, however, callClose()
directly as it only checks for theIDisposable
interface being implemented and hence theDispose()
method.See also:
这就是反射器解码代码生成的 IL 的方式:
所以答案是肯定的,如果满足以下条件,它将关闭连接:
throws an exception.
This is how reflector decodes the IL generated by your code:
So the answer is yes, it will close the connection if
throws an exception.
在此代码中不会调用 Dispose()。
Dispose() doesn't get called in this code.