2

在我的应用程序使用以下方式来调用DB:.NET检测分布式事务

//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(); 
} 

的问题是,Operation1和操作2 90%的时间使用相同的分贝......但也有他们使用两个数据库的情况下(错误)。如果交易分散,我想要得到一个异常。

如何检测交易是否被提升为分布式交易?

感谢,拉杜

回答

3

看一看的DistributedTransactionPermissionAttribute。它使用DistributedTransactionPermission类,这是当事务的管理升级到MSDTC(来自doc)时System.Transactions所要求的权限。

你可以将它应用到你的一段代码。升级时应提出安全异常。

+0

+1对于您的提示。现在,每当我的代码跨越该行时,我都会遇到异常。非常感谢 – 2012-11-07 12:41:16

0

当你TransactionScope正在进行中,你可以测试:

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

DistributedIdentifier被认为是空如果交易尚未晋升为分布式。从其文档中,备注部分:

如果事务升级为两阶段提交事务,则此属性返回其唯一标识符。如果交易未升级,则值为null

由于该属性不可为空,所以原则上显然是错误的。但是,使用ILSpy进行检查时,事务未分发时,它将替代为Guid.Empty(即default(Guid))。 (但也许一些非MSDTC分布式交易将不会尊重这一点。)