c# – Iterations within TransactionScope

Question:

I have an Asp.Net MVC project with Entity Framework 5.0 in .Net Framework 4.0.

What are the damages brought about by a very long TransactionScope ?

I have the following code snippet:

using(TransactionScope scope = new TransactionScope())
{
   foreach(var categoria in categorias)
   {
      // Sequencia de instruções
      db.Categoria.Add(categoria);
   }
   foreach(var produto in produtos)
   {
      // Sequencia de instruções
      db.Produto.Add(produto);
   }
   // Sequencia de instruções ou outra iterações.
   db.SaveChanges();
   scope.Complete();
}

Would it be somehow improved by splitting it into multiple Transactions?

Answer:

What are the damages brought about by a very long TransactionScope ?

Performance penalties, basically. If the transaction scope still asks for exclusive lock , the system as a whole slows down.

Would it be improved somehow by splitting it into multiple Transactions ?

It depends. If the entities don't have correlation, you can parallelize. Otherwise, because the context is not thread-safe , it is not possible to parallelize.

This doesn't mean it will get any faster. Parallelization is recommended for large volumes of data. For small transactions, the performance difference is not much felt.

Another thing you can do is use asynchronous methods, which improve concurrency between requests, but you'll have to go to .NET 4.5 and Entity Framework 6:

using(TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) // Só no .NET 4.5 em diante dá pra fazer isso
{
   foreach(var categoria in categorias)
   {
      // Sequencia de instruções
      db.Categoria.Add(categoria);
   }
   foreach(var produto in produtos)
   {
      // Sequencia de instruções
      db.Produto.Add(produto);
   }
   // Sequencia de instruções ou outra iterações.
   await db.SaveChangesAsync();
   scope.Complete();
}
Scroll to Top