1

I am having more then 20 transaction in in one shot. I want to use transaction scope with this. Is it possible? And If possible then what is the advantage of using transacation scope class over simple transaction.

What is the best practice to use transaction scope?

Jalpesh Vadgama
  • 13,653
  • 19
  • 72
  • 94

1 Answers1

5

The advantages of TransactionScope are:

  • you don't have to pass a transaction around (ADO.NET should enlist automatically)
    • which means that you can even use a TransactionScope to add transactions to existing, closed-source code (i.e. no changes are required)
  • a TransactionScope can (via DTC) span multiple resources (i.e. multiple databases, or a database and an MSMQ server, etc)

But you pay for this a little bit with speed. A connection-based transaction is slightly quicker (not much), but can only span a single resource and needs to be attached manually to all your DAL code. However, if you only talk to a single SQL2005/SQL2008 instance, then it can use the "LTM" - meaning it doesn't have to involve DTC (which is where most of the performance cost comes from) unless it absolutely needs to. Many TransactionScope operations can therefore complete talking only to the database.

If you want to span 20 operations, then TransactionScope should be ideal - it'll save you having to pass the transactions around, and allow each operation to manage their connection locally - making for highly re-usable code. Indeed, TransactionScope can be nested in the ways you expect, so you can have:

void Deposit(...) { /* uses TranScope to do a deposit */ }
void Debit(...) { /* uses TranScope to do a debit */ }
void Transfer(...) { /* uses a TranScope to span Debit/Deposit */ }

To do this using database transactions you'd need to pass the connection and transaction objects to each method, which quickly gets ungainly - especially if you need to code to work with/without an existing open transaction (lots of "if(tran==null)" etc).

For more information, see Transactions in .net

Community
  • 1
  • 1
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I found this pattern so useful I built my own similar structure for differing processes. – cjk May 12 '09 at 07:36