It seems like there is a lot of overhead involved in rapidly opening and closing sqlconnections. Should I persist a connection (one, per client, per database), or continue declaring a new sqlconnection object whenever I need one, and making sure I clean up after myself?
What have you done? What worked well and what worked poorly?
If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose . Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true or yes , the underlying connection is returned back to the connection pool.
If you want to access a database multiple times, you should establish a connection using the Connection object. You can also make a connection to a database by passing a connection string via a Command or Recordset object. However, this type of connection is only good for one specific, single query.
If you open the connection and don't close it, then it would decrease the connection pools and limits available for connecting to database again. It is always recommended to close the connection and data reader objects explicitly when you use them.
Note that SqlConnection instance is not guaranteed to be thread safe. You should avoid using the same SqlConnection in several threads at the same time. It is recommended to open a new connection per thread and to close it when the work is done.
In most cases, .NET connection pooling handles this for you. Even though you're opening and closing connections via code, that's not what's happening behind the scenes. When you instantiate and open a connection, .NET looks for an existing connection in the connection pool with the same connectionstring and gives you that instead. When you close the connection, it returns to the connection pool for future use.
If you're using SQL Server: http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx
OLE DB, ODBC, Oracle: http://msdn.microsoft.com/en-us/library/ms254502.aspx
Dino Esposito article: http://www.wintellect.com/Articles/ADO%20NET%20Connection.pdf
You can override default pooling behavior with connectionstring name/values: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx. See the second table of settings containing 'Connection Lifetime'.
There is not much overhead since, by default settings, pools are stored in the connection pool. Thus, when you open a connection, often you'll just get a ready connection from the pool. Creating SqlConnections has not given me any troubles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With