如果 SqlConnection
在 using
内执行期间抛出异常声明,我是否需要手动关闭 finally
中的连接?或者 using
的范围声明调用 Dispose
方法(在 SqlConnection
上)对我来说......因此执行 .Close();
我的方法(自动)?
例如:
using (var sqlConnection = new SqlConnection(_connectionString)
{
sqlConnection.Open();
throw new Exception("boom!");
}
对比
using (var sqlConnection = new SqlConnection(_connectionString)
{
try
{
sqlConnection.Open();
throw new Exception("boom!");
}
finally
{
sqlConection.Close();
}
}
此外,是否将其包装在 TransactionScope
中+抛出异常,影响我应该如何.Close()
或using
范围自动为我执行此操作。
最佳答案
不,如果它在 using
内,它仍然会被释放
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
Source : MSDN.
关于c# - 如果 .NET SqlConnection 在 `using` 语句内引发异常,我是否需要手动关闭它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32181948/