"sqlconnection thread-safe?" Code Answer


it's not a common way to share a sqlconnection, and it should be used only under special uses cases.

first, you're true that resource pooling is a common pattern used to improve performance when working with sockets, network streams, web services...

but especially for sqlconnection, you don't have to worry about this because the framework already do this for you, thanks to sql connection pool.

whenever a user calls open on a connection, the pooler looks for an available connection in the pool. if a pooled connection is available, it returns it to the caller instead of opening a new connection. when the application calls close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. once the connection is returned to the pool, it is ready to be reused on the next open call

you can consider sqlconnection as a wrapper around real connection. do not beleive that instanciating a new sqlconnection is costly : it's not and many web sites with high trafic are built with it.

the default strategy (for sql server at least) is that it will just work automatically. you just need to be aware of closing your connection (with a using block). there are also many settings to manage the pool.

you code also contains an incorrect error management : if the connection is aborted (dba, network failure, ...) you will throw exceptions when logging ... not ideal

at this end, i don't think that sharing a sql connection is appropriate in your case. you will gain much more perf using an async logging library.

do not focus on this now until you're sure it's a real problem.

we should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil, donald knuth

By Evonet on July 18 2022

Answers related to “sqlconnection thread-safe?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.