Last post Sep 21, 2012 08:07 PM by mbanavige
Sep 21, 2012 08:49 AM|achalk|LINK
.Net v4.0, VS2010
If I open an SqlConnection object inside a method, should I also close it within that method?
I ask because I use a meta tag to update a page every few seconds, creating a new SqlConnection (the handle is not assigned to a static variable.). After ten minutes the app. crashes apparently due to the exhaustion of resources and I think it may be these
Sep 21, 2012 09:10 AM|Dr. Acula|LINK
yes I would close it inside the method, I generally close a connection as soon as possible, I basically do
Sep 21, 2012 09:13 AM|Padmanabh007|LINK
The app crashes after ten minutes may be because of the number of opened SqlConnections that exceeds the default SQLConnection pool size. You should call the Dispose() method once you are done using the SQLConnection.
Following syntax in C# is an ideal practice for how you should use an SQLConnection (it automatically calls Dispose for you)
using(SQLConnection conn = new SQLConnection(connectionString))
// do stuff with conn
Sep 21, 2012 07:59 PM|achalk|LINK
Thank you both!
One other variant on this issue:
I have to use the SqlConnection() handle in several routines on the same page. Would it make more sense to create the connection in the OnLoad event and dispose of it in the UnLoad() event? I am thinking about the cost of constantly creating and tearing
down the connection in each function call.
Sep 21, 2012 08:07 PM|mbanavige|LINK
Would it make more sense to create the connection in the OnLoad event and dispose of it in the UnLoad() event?
close the connection in the same scope in which it was opened.
the framework will pool the connections, so that when you close a connection, it's not truly closed quite yet. instead, it's returned to the connection pool and is ready for reuse. on the next call to open a connection, that pool is checked first for a
matching connection thats available and already open. if one is found you get it automatically from the pool.