I am getting this error on my website:
Timeout expired. The timeout period elapsed prior to obtaining a
connection from the pool. This may have occurred because all pooled
connections were in use and max pool size was reached.Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.Exception Details: System.InvalidOperationException: Timeout expired.
The timeout period elapsed prior to obtaining a connection from the
pool. This may have occurred because all pooled connections were in
use and max pool size was reached.
This is the C# class that is being reused everywhere (I think the leak is here):
public class Generator
{
SqlConnection cn = null; // new SqlConnection(connectionString);
public SqlConnection Connection {
get {
if (cn == null) {
cn = new SqlConnection("Server=xxxxx,1433;Database=xxxxx;User ID=xxxxx;Password=xxxxx;Trusted_Connection=False;Encrypt=True;");
}
if(cn.State != ConnectionState.Open)
cn.Open();
return cn;
}
}
}
Then in my methods I use it like this:
var cmd = _generator.Connection.CreateCommand();
cmd.CommandText = "SELECT * FROM SomeTable";
var reader = cmd.ExecuteReader();
while (reader.Read())
{
//DO SOMETHING
}
reader.Close();
EDIT: In the class of my methods I attempt to share the same SQL connection across multiple methods like this:
private Generator _generator;
public HomeController()
{
InitializeConnection();
}
private void InitializeConnection()
{
_generator = new Generator();
}
Can anyone see how I can fix the leak or what is causing my max pool issue?
You need
usingblocks to make sure the objects are disposed.I also wouldn’t use a
Connectionproperty. It’s better to open and close connections as needed and allow connection pooling to do its job.