views:

208

answers:

1

I'm using Linq to SQL for a fairly complicated site, and after go live we've had a number of database timeouts. The first thing I noticed was there are a fairly large number of connections to the database.

Coming from an ADO.net background we used to code it so that any site would only use one or two pooled connections, and this resulted in acceptable performance even with a fair few concurrent users.

So my question is, was this old way of doing it flawed, OR is there a way to do it LINQ? It seems our performance issues are being caused by so many connections to the DB but if this was an issue I'd have thought it would be mentioned in all the tutorials for LINQ.

Any suggestions?

+2  A: 

I'm guessing that you are keeping DataContexts around and not calling Dispose on them when done (or leaving them around, at least).

Rather, you should initialize your DataContext, perform your operation, and then dispose of it when done. You shouldn't hold a reference to it between operations.

Preferably, you would use the using statement for handling the call to IDisposable.

Regarding connection pooling, the SqlClient pools connections by default, so unless you explicitly turn it off, you should be taking advantage of it already. Of course, if you aren't releasing connections you are using, then pooling will only take you so far.

casperOne
Doesn't the garbage collector take care of disposing the data context anway? Or do you mean that, on a high traffic site, there are too many DataContexts being opened in a short amount of time so that for small periods the garbage collector would be too late?
Adrian Grigore
@Adrian Grigore: The GC will ultimately take care of disposing the data context, but the data context holds an open database connection, so you want to explicitly close it when you are done.
casperOne
I've got the using datacontext in there so it's being disposed of properly. However I didn't realise i'd have to close the connection as well...is this documented anywhere?
ColinRobertson
@ColinRobertson: Calling dispose properly on the DataContext will close the connection. Are you using database connections elsewhere?
casperOne
@Colin: DataContext implements IDisposable. You are responsible for reclaiming resources. As long as there is a reference to the DataContext object in your code, no DB connections will be closed.
Theo Zographos
@Theo Zographos: Actually, that's incorrect, there are no DB connections that are open in LINQ-to-SQL when not performing an operation on the DataContext. Dispose actually does nothing. However, that's an *implementation* detail and should *not* be relied upon, one should always code against the contract, and in this case, call Dispose when done with a DataContext.
casperOne