Is there any consensus out there about whether it's best practice for a multi-threaded application to (1) use a single, shared, static connection to a SQL database, or (2) for each BackgroundWorker to open its own unique connection to the database?
I'm obviously assuming that each thread needs to connect to the same database.
And does the type of usage impact the answer? For instance, what if each thread is only running SELECT statements? Or if some threads may do UPDATE statements as well? Or does the usage not really make a difference, and you should always/never share a static connection regardless?
No. Of course not. Each thread needs its own connection.
Connection interface and is not thread-safe, according to its Javadoc: SQLServerConnection is not thread-safe, however multiple statements created from a single connection can be processing simultaneously in concurrent threads.
Absolutely not! This way the connection going to be shared among all requests sent by all users and thus all queries will interfere with each other.
The PostgreSQL™ JDBC driver is thread safe. Consequently, if your application uses multiple threads then you do not have to worry about complex algorithms to ensure that only one thread uses the database at a time.
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.
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