Question

When developing an application (web, win, whatever) which does alot of data access, is it better to keep your data access object open for the length of the request (i.e. do many things in a row, then close it when you finish), or keep opening and closing new ones?

protected aDataContext dc = new aDataContext();

vs

private aObject GetInfo(...) {...}

I would think the former would be better for performance; but it seems like a bad practice.

Was it helpful?

Solution

Typically you should open a new connection for every unit of work, use it and then close it as soon as possible. Internally .NET (or ADO or ODBC or whatever) will pool connections for you, so long as the connection string is the same, therefore it's actually very efficient. There are other issues to take into account - particularly transactions - but in general it's best to follow this pattern of open-do-close and let .NET manage the connection pool.

OTHER TIPS

Better use a connection pool. keep a limited number of connections open as much as you can. Opening a connection is pricey, yet having million open connection might kill your server. you should benchmark your scenario for best results....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top