Is it best practice to use a static database connection across multiple threads? Is it best practice to use a static database connection across multiple threads? database database

Is it best practice to use a static database connection across multiple threads?


As discussed on the comments of your question. The best practice would be to leave the connection handling to ADO.Net as it contains connection pooling control so all you should do is open a connection every time you need execute a bit of SQL and then close it. The connection pool will not immediately close the connection as it will leave it open for configurable time to be able to pass it over to other threads requesting a new connection to be open. Additionally connections are not thread safe so each thread should have its on connection but again ADO.Net will deal with that.

If you want to learn more about the connection pool i suggest the following MSDN article: http://msdn.microsoft.com/en-us/library/8xx3tyca(v=vs.110).aspx

I also highly recommend that you read Microsofts Best practices for ado .net here: http://msdn.microsoft.com/en-us/library/ms971481.aspx

Some other articles:


From the DbConnection (or SqlConnection) documentation:

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

So a connection object is not thread safe, meaning you should not share a connection instance across multiple threads.