.NET, the SqlConnection object, and multi-threading .NET, the SqlConnection object, and multi-threading multithreading multithreading

.NET, the SqlConnection object, and multi-threading


The obvious solution is to just re-create the SqlConnection object every time a database call requires one - in this case, it would never be shared. Is there any reason not to do this?

On the contrary, that's absolutely what you should do. That's the behaviour SqlConnection was designed for. You should use a Using statement to automatically close the connection at the end of the block you're using it for, and the connection pool mechanism will automatically handle the real underlying connections to the database.


I see no reason NOT to create a SQL connection every time you need it. In fact, that is probably the best way to do it because it gives the .NET framework the flexibility to manage and reuse connections most efficiently. Wrap each of your SQL connections in a USING so you hang on to them as short a time as possible.

We've created a method that creates a connection and everyone uses that:

using (var conn = GetConnection())    using (var proc = GetProcedure(conn, "procname"))        using (var reader = proc.GetReader())        {            ... DB stuff        }