c# - 连接没有像它应该的那样关闭

标签 c# asp.net sqlconnection

我在我的 ASP 项目中遇到以下错误:

The connection was not closed. The connection's current state is open

在 SqlConnection 对象上调用 .open() 函数时。

我已经试过了:

    if (Conn.State != ConnectionState.Closed)
    {
        Log.Message(xxx);
        try
        {
            Conn.Close();
        }
        catch (Exception ex)
        {
            Log.Error(xxxx);
        }
    }
    Conn.Open();

但这仍然会引发错误。 Conn 对象声明为:

private static readonly SqlConnection Conn = new SqlConnection(xxxx);

我应该在哪里寻找解决方案的任何想法

最佳答案

这是模式。

using(var conn = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(someSql, conn)
{
    conn.Open();
    cmd.ExecuteNonQueryOrWhatevs();
}
  1. 建立联系
  2. 打开你的连接
  3. 处理你的连接

不要尝试重复使用它。获取它、使用它并尽快处理它。

此外,这些都不是线程安全的,所以不要从不同的线程中接触上述任何实例。请一个线程仅使用连接。随意使用多线程来处理结果。

关于c# - 连接没有像它应该的那样关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24141428/

相关文章:

c# - Windows Phone 8.1 XAML 应用程序。如何防止不恰当的自动调焦?

c# - Visual Studio 2015 社区 - 正则表达式查找和替换

c# - Entity 6 + PostgreSQL - 糟糕的性能

c# - 开源 3D 几何库?

asp.net - 如何为 ASP.NET Core 应用程序配置 IIS 身份验证以使用 SQL Server

c# - 使用 sql 连接的最佳/标准方法是什么?

c# - ASP.NET MVC 中的 “File does not exist”

asp.net - 基准测试时 Razor 页面中的 BookSleeve Wait() 超时

sql-server - 新 SQL Server 连接的方法/属性错误

c# - ASP.NET使用SqlConnection连接MySQL