2

在我的应用程序中,我使用以下模式调用数据库:

    //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 和 Operation2 90% 的时间使用相同的数据库……但是当他们使用两个数据库时存在一些情况(错误)。如果事务变得分布式,我想得到一个异常。

如何检测事务是否提升为分布式事务?

谢谢,拉杜

4

3 回答 3

5

你也可以看看下面的活动

TransactionManager.DistributedTransactionStarted 事件

于 2010-11-25T08:55:02.100 回答
3

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

您可以将其应用于您的代码。升级时应引发安全异常。

于 2010-11-25T08:49:21.870 回答
1

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

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

DistributedIdentifier如果事务尚未提升为分布式,则称该事务为空。从其文档,备注部分:

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

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

于 2017-05-12T18:05:53.317 回答