Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downside of using TransactionScope RequiresNew

I want to understand what is the trade-of/downside of using TransactionScopeOption.RequiresNew on EntityFramework (w/ Sql Server 2008), what are the reasons why we should NOT use RequiresNew always.

Regards.

like image 489
Bongo Sharp Avatar asked Apr 22 '11 22:04

Bongo Sharp


People also ask

What is the use of TransactionScope in C#?

The TransactionScope class provides a simple way to mark a block of code as participating in a transaction, without requiring you to interact with the transaction itself. A transaction scope can select and manage the ambient transaction automatically.

What is ambient transaction?

An ambient transaction is one that works at the thread level. Thus, all operations that occur in that context will be part of the transaction.

What is transaction scope in SQL Server?

The TransactionScope class makes a code block transactional by implicitly enlisting connections in a distributed transaction. You must call the Complete method at the end of the TransactionScope block before leaving it. Leaving the block invokes the Dispose method.

What is transaction scope in Entity Framework?

Entity Framework is already operating within a TransactionScope. The connection object in the transaction passed is null. That is, the transaction is not associated with a connection – usually this is a sign that that transaction has already completed.


1 Answers

You should use Required not RequiresNew. RequiresNew means every operation will use a new transaction, even if there is an encompassing already existing transaction scope. This will certainly lead to deadlocks. Even with Required there is another serious problem with TransactionScope, namely that it creates by default a Serializable transaction, which is a horribly bad choice and yet another shortcut to deadlock hell and no scalability. See using new TransactionScope() Considered Harmful. You should always create a transaction scope with the explicit TransactionOption setting the isolation level to ReadCommitted, which a much much much more sane isolation level:

using(TransactionScope scope = new TransactionScope(
    TransactionScopeOption.Required,
    new TransactionOptions {
       IsolationLevel = IsolationLevel.ReadCommitted}))
{
   /// do work here
   ...
   scope.Complete();
}
like image 181
Remus Rusanu Avatar answered Sep 26 '22 02:09

Remus Rusanu