Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TransactionScopeOption - Required or RequiresNew

I'm currently having a confusion concerning the constructor of the TransactionScope object.

Say that users of my website can order products. On submitting their request, I carry out a verification of the current quantity left and if it is still greater than zero, I carry out the request. Then, at the end I decrement the current quantity left.

The whole process is within a transaction, using .NET transactionScope.

After reading several articles on .NET transactionScope object, I'm now a bit confused about the value of the TransactionScopeOption to use for the constructor of the transactionScope.

Which one of the following is more appropriate for the case described above:

public void ProcessRequest()  
 {  
     TransactionOptions transactionOptions = new TransactionOptions();  
     transactionOptions.IsolationLevel = IsolationLevel.Serializable;  
     using (TransactionScope currentScope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOptions)) {  
      // DB Query to verify if quantity is still greater than zero  
      // DB Query to request and decrement quantity 
      currentScope.Complete();
     }  
 }  

OR

public void ProcessRequest()  
 {  
     TransactionOptions transactionOptions = new TransactionOptions();  
     transactionOptions.IsolationLevel = IsolationLevel.Serializable;  
     using (TransactionScope currentScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) {  
      // DB Query to verify if quantity is still greater than zero  
      // DB Query to request and decrement quantity 
      currentScope.Complete();
     }  
 }  

Note that the above is just an over simplification of my actual problem. I'm only interested in knowing the right value of the TransactionScopeOption (RequiresNew or Required) for such a case.

Thanks for replying.

like image 329
Abhisheik Coomar Motee Avatar asked Jan 07 '11 19:01

Abhisheik Coomar Motee


1 Answers

It depends what you want to happen if another method calls ProcessRequest inside another transaction:

public void SomeOtherMethod() {
    using (TransactionScope ts = new TransactionScope()) {
        // Another DB action
        ProcessRequest();
        // Yet another DB action
    }
}

If you want ProcessRequest to use the transaction created by SomeOtherMethod, use TransactionScope.Required. This is the default (and it still creates a transaction when you call it without having created another transaction scope up the call stack).

If you want it to force this method to always use its own (new) transaction, use TransactionScope,RequiresNew.

like image 69
Jeff Sternal Avatar answered Sep 21 '22 05:09

Jeff Sternal