在下面的示例中,如果在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();
}