Thursday, June 25, 2009

Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool.


I keep getting the following errors on one of my application sites after clicking for many times:

"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."


Below was my code:

SqlConnection conn = new SqlConnection(DataAccess.GetConnectionString());
conn.Open();
SqlDataSource1.SelectCommand = sql;
SqlDataSource1.SelectParameters.Clear();
Repeater1.DataSource = SqlDataSource1;
Repeater1.DataSourceID = string.Empty;
Repeater1.DataBind();
conn.Close();


I found later, this typically happens when connections are not closed after they are used. You should put everything in a try/catch/finally, with the connection being closed in the Finally to ensure that it always gets closed no mater what.

Hence the solution is:

SqlConnection conn = new SqlConnection(DataAccess.GetConnectionString());
conn.Open();
try
{
SqlDataSource1.SelectCommand = sql;
SqlDataSource1.SelectParameters.Clear();
Repeater1.DataSource = SqlDataSource1;
Repeater1.DataSourceID = string.Empty;
Repeater1.DataBind();
}

finally
{
SqlConnection.ClearPool(conn);
SqlConnection.ClearAllPools();
}

Note: If there is any return statement before you close the connection, there might be a connection leak ; be careful on that.

No comments:

Post a Comment

Highly Appreciated your comments