gpt4 book ai didi

c# - 如果我在 SqlConnection 的 using 语句中捕获异常,using 是否仍然处理关闭和处理我的连接?

转载 作者:太空宇宙 更新时间:2023-11-03 22:23:30 25 4
gpt4 key购买 nike

我正在 ASP.NET 应用程序中检查一些旧的 C#.NET 代码,确保所有 SqlConnections 都包含在 using block 中。

这段代码用于打开cnda并在catch block 和方法末尾处理它们.我添加了 usings 并且无法确定如果在 try 中抛出异常,using block 是否仍然处理连接处理> 并陷入了陷阱This question似乎表明确实如此。

using (SqlConnection cn = new SqlConnection(Global.sDSN))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
// do some stuff
try
{
// do stuff that might throw exceptions
}
catch (catch (System.Exception e)
{
//return something here
// can I ditch these because the using's handle it?
da.Dispose();
cn.Close();
cn.Dispose();
return msg;
}
}
}

最佳答案

是的,他们会的。它们基本上变成了 finally block 。

所以像这样:

using (SqlConnection cn = new SqlConnection(Global.sDSN))
{
....
}

真的变成了:

SqlConnection cn = new SqlConnection(Global.sDSN)
try
{
....
}
finally
{
cn.Dispose();
}

或多或少 - finally block 总是执行,无论之前在 try {.....} block 中发生了什么。

关于c# - 如果我在 SqlConnection 的 using 语句中捕获异常,using 是否仍然处理关闭和处理我的连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2313082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com