Sql – Is it possible to gets sql connection leaks using LINQ

connection-poolinglinq-to-sqlnet

I belived it was not possible to get sql connection leaks when using LINQ, but perfmon tracing of NumberOfReclaimedConnections shows a high number and on high load we sometimes get exceptions like "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".

We do not use Dispose on the datacontexts, sincewe used defered loading. Several articles and blogpost tells me that this should not be a problem.

Still we gets these exceptions sometimes. But it can not be that every linq query we do keep the connection open, then we would have a lot more of the exceptions.

Edited

The application is a WCF service.

If you look at the documentation of Linq and most of the articles, they claim that the Dispose is not necessary to release the connections. They claim that DataCOntext only keep the connection open for the short time it need it.

Best Answer

When your DataContext is not disposed of and stays alive, the associated connection will stay alive too. Database connections are unmanaged resources and all unmanaged resources must be disposed of properly.

Even if you use delay-loading and do not have a well-defined scope, you should still clean up database connections at the end of a logical unit of work. In ASP.NET apps, the latest possible moment for this would be at the end of request processing - in the Application_EndRequest method of the Globals.asax file. In a WCF service, any active data context should be disposed of at the end of every service method call.

The documentation for this is vague and while most of the time, you can get away with not disposing your DataContext, there do appear to be some scenarios where the data loaded from a connection is keeping the connection itself alive. The easiest way to confirm that this is happening in your case is to test it.

Related Topic