【问题标题】:Random behavior: "The connection was not closed. The connection's current state is open."随机行为:“连接未关闭。连接的当前状态为打开。”
【发布时间】:2014-05-06 16:04:27
【问题描述】:

这很奇怪,虽然这段代码经常执行,但它只是偶尔发生。

我让这段代码每 5 秒运行一次,它运行良好,但有时我会将异常保存在我的日志中。

异常消息:连接未关闭。连接的当前状态是打开的。

 public class Log
{

    static SqlConnection sqlConnection{get; set;}

    public Log()
    {
        sqlConnection = new SqlConnection(CNN_STRING);
    }



    public static void Save(){
        StringBuilder sb = new StringBuilder();

        sb.Append("UPDATE Blabla SET ...");

        SqlCommand command = new SqlCommand(sb.ToString(), sqlConnection);


         try
        {
            if (sqlConnection.State == ConnectionState.Open) { sqlConnection.Close(); }
            sqlConnection.Open();
            command.ExecuteNonQuery();
            sqlConnection.Close();
        }catch(Exception e){
            Log.AddLog("Log ", 1, string.Concat("Query: ", sb.ToString(), 
                       "Exception    message: ", e.Message));
        }
        finally
        {
            if (sqlConnection.State == ConnectionState.Open) { sqlConnection.Close(); }
        }
   }

有什么线索吗?

【问题讨论】:

  • 考虑使用using statement来处理你的SqlConnectionSqlCommand
  • 如果连接已经打开,为什么要关闭它并重新打开它?这不是最快的,而且有成本。当您尝试再次打开连接时,很可能连接仍在关闭。
  • 显示sqlConnection的声明,是static吗?然后让它成为一个局部变量,你就完成了。
  • @TimSchmelter 它是静态的,因为方法也是静态的
  • 我的意思是,它是一个静态类,有一些使用连接的静态函数

标签: c# asp.net sql asp.net-mvc exception


【解决方案1】:

静态连接对于 ASP.NET 来说不是一个好主意,因为每个请求都会共享此连接,这将导致最好的锁定甚至像您这样的错误。

也许我前段时间发布的this answer 有帮助。所以不要让它成为静态的并使用using-statement。

using(var sqlConnection = new SqlConnection(CNN_STRING))
using (var command = new SqlCommand(sb.ToString(), sqlConnection))
{
    sqlConnection.Open();
    command.ExecuteNonQuery();
}

您不需要关闭连接,因为这是由 using-statement(dispose) 完成的。

【讨论】:

  • 感谢您的链接,现在我必须更改 600 行代码,因为我将 ADO.NET 功能封装到 DB 辅助类中!
  • 顺便说一句,“使用”总是会关闭/释放连接,对吧?
猜你喜欢
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
  • 2023-01-11
  • 1970-01-01
相关资源
最近更新 更多