【问题标题】:Will return keyword inside using statement, leave the connection open?将在 using 语句中返回关键字,保持连接打开?
【发布时间】:2015-08-04 09:23:22
【问题描述】:

我们在 SqlConnection.Open() 上遇到 Timeout expired 异常。

下面是代码:

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 关键字是否使连接保持打开状态并因此出现此问题?

【问题讨论】:

  • 因为它是 try finally 语句的语法糖,所以不会。
  • 这个有很多骗子,但无法选择。

标签: c# ado.net database-connection sqlconnection timeoutexception


【解决方案1】:

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

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

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

请注意,您可以通过删除 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();
        }
    }
}

同样,命令和连接仍然会被适当地处理。

【讨论】:

  • 谢谢乔恩。是的,这一次被多个用户调用。上面的代码会阻止Timeout异常吗?
  • @sth:不,我提供的代码 sn-p 在功能上是等效的,但比您当前的代码更简单。根据您有多少并发用户以及存储过程运行所需的时间,您可能只需要增加连接池的大小 - 但我们不知道足够的上下文来说明。
  • 我希望增加连接池大小不会有任何副作用。
  • @sth:你的数据库还有更多工作要做——但基本上我们不知道这是否是个问题,因为我们没有上下文。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
  • 1970-01-01
相关资源
最近更新 更多