Question

In my application I use the following pattern for calling the DB:

    //do a transaction 
using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.Required))
{
    OperationOnDb1();

    //when we open the connection to the “other db” in this call, the transaction would become distributed
    OperationOnDb2();

    //transaction is now distributed
    transaction.Complete();
}

The problem is that Operation1 and Operation2 90% of the time use the same db ... but there are cases (bugs) when they use two DBs. I want to get an exception if the transaction becomes distributed.

How can I detect if the transaction is promoted to a distributed transaction?

Thanks, Radu

Was it helpful?

Solution

You can also have a look at the following event

TransactionManager.DistributedTransactionStarted Event

OTHER TIPS

Have a look at the DistributedTransactionPermissionAttribute. It's using the DistributedTransactionPermission class wich is the permission that is demanded by System.Transactions when management of a transaction is escalated to MSDTC (from doc).

You could apply it to your piece of code. A security exception should be raised on escalation.

While your TransactionScope is ongoing, you may test:

Transaction.Current.TransactionInformation.DistributedIdentifier != default(Guid)

DistributedIdentifier is said to be null if the transaction is not yet promoted to distributed. From its documentation, remarks section:

If the transaction is escalated to a two-phase commit transaction, this property returns its unique identifier. If the transaction is not escalated, the value is null.

Since this property is not nullable, this is obviously wrong in principle. But checking with ILSpy, it is Guid.Empty instead (which is default(Guid)) when the transaction is not distributed. (But maybe some non MSDTC distributed transaction will not respect that.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top