views:

37

answers:

2

How goes it everybody?

Very simple question today. If I give two separate Threads two different SqlCommands. If both SqlCommands use the same SqlConnection, can they execute at the same time? Does SqlConnection block this behavior? Or does something... more interesting happen?

(I do believe SqlConnections are pooled by connection string for this exact reason, but I just need some reassurance)


This is a hypothetical question, just curious how SqlConnection behaves given the design described.

+1  A: 

With ADO.NET connection pooling in place, the proper way to run a query is to create and open a connection object, then run a command object (which uses the connection object), and then close the connection. So the scenario you describe (where you hand an open connection to two different command objects) should never occur. In normal usage your two different command objects should open and close their own connection objects independent of each other, which means you will never run into the problem of two command objects simultaneously attempting to use the same connection at the same time.

MusiGenesis
I am aware of this, but lets say, hypothetically we do use the design I described. What would SqlConnection behave like?
Meiscooldude
I think if you have two command objects trying to execute from the same connection at the same time, the second command will throw an error like "There is already an open DataReader associated with this Connection". You could catch this exception and try again, or implement a locking mechanism so that the command objects never execute simultaneously. Or even better, you could just create a new connection, execute the command, and close the connection (letting ADO.NET handle the problem of shared connections for you).
MusiGenesis
So, it will throw an exception on the attempt to execute the second command? Alright, thats what I was curious about.
Meiscooldude
A: 

Maybe you should consider Multiple Active Result Sets. You can execute multiple queries on a single SqlConnection object although with certain limitation.

alwayslearning
executing multiple queries on the same connection is not my goal. I'm debugging a program and found that this scenario was happening. So I'm probably just going to redesign it.
Meiscooldude

related questions