【发布时间】:2010-10-05 19:46:43
【问题描述】:
在下面的示例中,如果在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?【问题讨论】:
标签: c# asp.net using-statement