Search code examples
c#asp.netiis-7database-connectionconnection-pooling

ASP.net Timeouts due to connections not being closed


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 first ASP.net site I developed a long time ago, it has this code at the top of a lot of pages (and in a lot of methods).

cn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString());
cn.Open();

A lot of pages don't have:

cn.Close();

Also none of the pages do using(SqlConnection...), (although all the data readers are in using blocks).

First question is, is the the primary candiate for the error?

Second question is, is the best way to solve this refactoring/manually searching for unclosed connections? I know it's an ugly hack, but the time spent refactoring will be huge, but can we set a scheduled task to recycle the connection pool once a day at 3am or something?


Solution

  • Yes, that is the primary cause of the error. Currently, many of those connections will wait until the next GC to re-pool the underlying connection. You will exhaust the pool (and database connections) pretty quickly.

    The best way of refactoring this is to add the missing using, such that the connection is scoped. Personally I'd also refactor that to a single method, i.e.

    using(var cn = SomeUtilityClass.GetOpenConnection())
    {...}
    

    Closing the reader does little unless the reader is marked to close the connection; and having the data-reader close the connection (via a behaviour) sort of works, but it assumes you get as far as consuming the reader - it won't necessarily behave well in error scenarios.