gpt4 book ai didi

c# - 将在 using 语句中返回关键字,保持连接打开?

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

我们在 SqlConnection.Open() 上收到超时过期异常。

代码如下:

public int ExecuteNonQuery(SqlParameter[] param, string strSPName)
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
int i = 0;
using (SqlCommand cmd = new SqlCommand(strSPName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(param);
conn.Open();
i = cmd.ExecuteNonQuery();
}
return i;
}
}

using 语句中的 return 关键字是否使连接保持打开状态并因此出现此问题?

最佳答案

Does the return keyword inside the using statement leaving the connection to opened and hence this issue?

没有。 using 语句实际上是 try/finally block 语句 finally 部分中的 Dispose 调用 - 因此您的连接仍将在最后处理方法。

我怀疑或者您只是同时从太多线程调用它并以这种方式耗尽您的池,或者您在其他地方打开连接而不关闭它。

请注意,您可以通过删除 i 局部变量来简化代码:

public int ExecuteNonQuery(SqlParameter[] param, string strSPName)
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand cmd = new SqlCommand(strSPName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(param);
conn.Open();
return cmd.ExecuteNonQuery();
}
}
}

同样,命令和连接仍将被适当处理。

关于c# - 将在 using 语句中返回关键字,保持连接打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31805426/

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