How to use TransactionScope properly?

Denis picture Denis · Jan 4, 2013 · Viewed 46.3k times · Source

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

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?

Answer

Trevor Pilley picture Trevor Pilley · Jan 4, 2013

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.

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.