0

I've seen examples of code where a TransactionScope is nested inside another like this

using(TransactionScope scope1 = new TransactionScope())
{
     try
     {
          //Start of non-transactional section 
          using(TransactionScope scope2 = new
             TransactionScope(TransactionScopeOption.Suppress))
          {
               //Do non-transactional work here
          }
          //Restores ambient transaction here
   }
     catch
     {}
   //Rest of scope1
}

I can understand here the use of Supress but as far as I understand Required just merges with the outer Transaction, so that if anything fails, the whole thing fails, so what's the point? Am I missing something here?

EDIT: Just to be clear I want to emphasize that the Suppress option I (think I :-)) understand, which is explained in the MSDN documentation. My question is on the default Required option; maybe I don't fully understand but if Transaction B is nested inside Transaction A then if either A fails or B fails then both A and B will be rolled back, which is the same if I never put B in a transaction in the first place.

So the question reworded is 'What is the difference between nesting a Transaction with the default Required option, and not doing it all?'

happygilmore
  • 3,008
  • 4
  • 23
  • 37
  • 1
    have you read the MSDN example and explanation on [TransactionScope](http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx) – MethodMan Feb 11 '13 at 18:01
  • @DJKRAZE if I am quoting the MSDN page with a back link included, then most probably yes. – happygilmore Feb 12 '13 at 08:27

1 Answers1

0

Think about this:

using(TransactionScope scope1 = new TransactionScope())
{
     //i insert some records in tabe A
     try
     {              
          using(TransactionScope scope2 = new
             TransactionScope(TransactionScopeOption.Suppress))
          {                  
               // I insert some records in table B
               scope2.Complete() 
          }
          //I insert some records in table C
   }
     catch
     {}
   //I Update some records in table D
   //I Delete some records of table E
   // Here we have an exception being thrown                       
 scope1.Complete() 
}

after running the code
all changes to tables A,C,D,E will be rolled back
all changes to table B will be committed

TrnsactionScop Down side

Community
  • 1
  • 1
Mohsen Heydari
  • 7,256
  • 4
  • 31
  • 46
  • B runs without any transaction. There is no transaction there to be committed. The statement about a c d and f is correct (given that there is no `scope1.Complete()` call). Hint you mention B, but it is nowhere in your code. – Christian.K Feb 11 '13 at 19:18
  • my question was regarding the default Required option, not the Suppress. I'm going to edit my question to make this more clear. – happygilmore Feb 12 '13 at 08:14