[英]Will connection leak might Cause Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool?
[英]Timeout expired. The timeout period elapsed prior to obtaining a connection First connection
我有这个问题。 我已经在很多网站上搜索了此问题,但所有这些网站都建议关闭所有连接,或者仅对连接和dataReader使用“使用”。 但! 我的问题在于无法打开第一个连接! 我在连接附近设置了一个断点,然后看到没有其他连接,因此有第一个连接。 当我重新创建从静态到Singleton的开放连接的类时,此问题出现了,这是代码:
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();
}
引发异常时,连接为Closed
。 有人有想法吗?
更新:
如果我关闭池-在同一行的"System.StackOverflowException" in System.Data.dll
中有"System.StackOverflowException" in System.Data.dll
。
您的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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.