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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With