c# - 超时已过。在获得连接之前超时时间已过 首次连接

标签 c# sql-server design-patterns connection-pooling

我有这个问题。我用谷歌搜索了很多有这个问题的网站,但他们都建议关闭所有连接,或者只使用“using”连接和 dataReader。但!我的问题是我无法打开第一个连接!我在连接附近设置了一个断点,发现没有其他连接,所以有第一个。当我重新制作从静态到单例打开连接的类时,这个问题就出现了,这里是代码:

public class Storage
{
private static Storage instance;

public static Storage Instance
{
    get
    {
        if (instance == null)
        {
            instance = new Storage();
        }
        return instance;
    }
}

private Storage()
{
    Manager man = new Manager();
    products = man.LoadProducts();
    components = man.LoadComponents();
    man.LoadProductComponents();
}

public Dictionary<int, Product> Products
    {
        get { return products; }
        set { products = value; }
    }

public Dictionary<int, Component> Components
    {
        get { return components; }
        set { components = value; }
    }

private Dictionary<int, Product> products;
private Dictionary<int, Component> components;

}

这是一个Manager构造函数

    public Manager()
    {
        connection = new SqlConnection(@"Persist Security Info=False;User ID=user;Password=pass;Initial Catalog=Products;Server=(local)");
        if (connection.State != ConnectionState.Open) connection.Open();
    }

当出现异常时,连接关闭。有人有想法吗?

更新:

如果我关闭池 - 我在同一行的 System.Data.dll 中有 “System.StackOverflowException”

最佳答案

您的 Manager 类创建并打开一个连接:

public Manager()
{
    connection = new SqlConnection(@"Persist Security Info=False;User ID=user;Password=pass;Initial Catalog=Products;Server=(local)");
    if (connection.State != ConnectionState.Open) connection.Open();
}

但是,如果我们看看您是如何使用它的,很明显没有任何东西关闭这个连接:

private Storage()
{
    Manager man = new Manager();
    products = man.LoadProducts();
    components = man.LoadComponents();
    man.LoadProductComponents();
}

我希望 Manager 实现 IDisposable,并让 Dispose() 方法关闭并释放连接:

class Manager : IDisposable
{
    ...
    public void Dispose()
    {
        if(connection != null) connection.Dispose();
        connection = null;
    }
}

然后将通过 using 使用:

private Storage()
{
    using(Manager man = new Manager())
    {
        products = man.LoadProducts();
        components = man.LoadComponents();
        man.LoadProductComponents();
    }
}

我担心的是,您的经理只是一个更广泛问题的一个例子:没有在您自己之后清理连接。当 Manager 是静态的时,这可能是完全不可见的,但是当切换到 Manager 实例时,很容易启动多个 Manager对象。在 GC 之前,每一个都绑定(bind)一个连接。

关于c# - 超时已过。在获得连接之前超时时间已过 首次连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15083740/

相关文章:

asp.net - 具有 100 个字段的网络表单的良好模式或技术

java - 为什么构建器模式使用 new 关键字,尽管它的构造函数是私有(private)的?

c# - 如何创建虚拟音频设备

sql-server - 带有插入时间的 T-SQL 代码片段

c# - 是否有将 T-SQL 存储过程转换为 C# 的工具?

Erlang 二进制模式匹配未知数量

c# - 此应用程序只能在应用程序容器的上下文中运行

c# - 格式化数字作为排名位置

c# - MVC @Html.DropDownList 在 ViewBag 中使用 SelectList 时出错

SQL重复优化