1

In .NET, when we use TransactionScope we can share a same transaction across multiple connections.

using(TransactionScope tran = new TransactionScope()) { 
  //this method open a new connection
  CallAMethodThatDoesSomeWork(); 
  //this method open another new connection
  CallAMethodThatDoesSomeMoreWork(); 
  tran.Complete(); 
}

I can't understand how it is possible, taking account that a transaction need a specific connection to run in the database.

How is it working? I think that maybe the physical connection is always the same. Could be this possible?

Update: suppose that the connection string is the same for all connections, i.e. I don't work with different databases, is always the same...

  • Through the magic of [the Distributed Transaction Coordinator](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/distributed-transactions) – Crowcoder May 26 '19 at 21:39
  • I forgot to mention that I am working with the same connection (same DB, same connection string). – user3384718 May 26 '19 at 21:54
  • It doesn't matter. I don't pretend to understand it well, but the DTC is responsible for enlisting transactions and handles voting, and more magic. If you are familiar with Windows Communication Foundation, you can even enlist layers of service calls in a transaction! DTC is not specific to SQL Server. – Crowcoder May 26 '19 at 22:14
  • Have you read the following? https://learn.microsoft.com/en-us/dotnet/framework/data/transactions/ this is a good place to start. – Richard May 26 '19 at 22:21
  • 2
    @Crowcoder for completeness - the "lightweight transaction manager" (LTM) may be able to deal with some of this rather than involving the DTC, especially if everything is going to the same server (same connection string and domain account). It may also depend a bit on whether they are sequential or concurrent. – Marc Gravell May 26 '19 at 23:41
  • Lots of useful info in this question https://stackoverflow.com/questions/1690892/transactionscope-automatically-escalating-to-msdtc-on-some-machines – Rory Nov 04 '21 at 12:20

1 Answers1

2

Thanks to the comments I was able to find the answer here.

When we use TransactionScope we can share a same transaction across multiple connections because this transaction is converted to a distributed transaction; and the Distributed Transaction Coordinator (DTC) do its magic.

In general, even when the connections are to the same DB, TransactionScope will escalate to DTC.

The exception to the rule could be when we open and close different connections to the same DB not simultaneously; but this isn't supported by all DB engines.