简体   繁体   中英

Multiple connections to the same DB in the same TransactionScope

How are the connections handled in a single transaction when we open close connections for each statement in C#?

The scenario is with the same connection string and the connection is opened and closed multiple types, once for every statement.

Consider the following example

void updateSomething() {
    using (SqlConnection connection = new SqlConnection(  
      "Integrated Security=SSPI;Initial Catalog=Northwind"))  
    {  
        connection.Open();        
        // Execute the statements
        connection.Close();  
    }  
 }

When I'm executing the following code:

void SomeMethod()
{
    using(TransactionScope scope = new TransactionScope())
    {
        for(int i=0; i < 10; i++) 
        {
            this.updateSomething();
        }
        scope.Complete();
    }
}

The recommendation is to use a connection Open/Close for each statement. That is because we are not actually creating connections, we are just using one from the pool.

Why is this the case? I get it that we hold the connection for as little time as we can, but the thing is that in most transactions, we are going to get it in the next moment during the next statement.

Is it only to avoid the demanding code computation time in between the statements if some such exists (which it shouldn't as it would lock the database in the transaction state for much longer that needed).

Wouldn't it make sense to keep one connection open for the duration of the transaction?

The recommendation is to use a connection Open/Close for each statement.

Without seeing that comment in context, I'm guessing this recommendation is because of what you said: creating and destroying a SqlConnection objects does not mean you are creating and destroying network connections.

I think the motive behind "use one for each statement" is to just not worry about trying to be efficient about when you create SqlConnection objects. Don't go out of your way to keep one alive and pass it around all throughout your code thinking you are avoiding tearing down a network connection. There's just no point.

In your example, it won't really make a difference. You can use the same SqlConnection object for each query if you'd like, as long as you are making them sequentially and not in parallel. It's probably even slightly more efficient since you save the computational time of creating an SqlConnection object. But that saved time will likely not even be noticeable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM