如何使用TransactionScope的正确?如何使用、正确、TransactionScope

2023-09-04 01:30:21 作者:勇气都没了

我总是想尝试使用的TransactionScope 但我想不出什么人看到它是有用的。所以,让我们看一个例子:

I always want to try to use TransactionScope but I just can't figure out what people see about it that is useful. So let's take an example:

using(TransactionScope tran = new TransactionScope()) {
    CallAMethodThatDoesSomeWork1();
    CallAMethodThatDoesSomeWork2();
    tran.Complete();
}

因此​​,最根本的问题:我如何写 CallAMethodThatDoesSomeWork1(),使其知道如何推出它的行动回来,如果让我们说 CallAMethodThatDoesSomeWork2()抛出一个异常?

So the most basic question: How do I write "CallAMethodThatDoesSomeWork1()" so that it knows how to roll its actions back if let's say "CallAMethodThatDoesSomeWork2()" throws an exception?

推荐答案

在你调用方法的code需事务感知并争取在活动事务中。这意味着创建或使用类,它们都是资源管理器(请参阅Implement您自己的资源管理器。

The code within the methods you call need to be transaction aware and enlist in the active transaction. This means creating or using classes which are resource managers (see Implement Your Own Resource Manager.

您做到这一点通过实施IEnlistmentNotification并争取在交易。当交易完成时,该接口使您的code可以做/撤销工作。

You do this by implementing IEnlistmentNotification and enlisting in the transaction. When the transaction is completed, the transaction manager will call methods as defined on that interface so that your code can do/undo the work.