Iterations within TransactionScope

3

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

What are the losses brought 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 improved by somehow splitting into multiple Transactions?

    
asked by anonymous 08.06.2016 / 20:55

1 answer

2
  

What are the losses brought by a very long TransactionScope ?

Performance penalties, basically. If the transaction scope still requests exclusive lock , the system as a whole is slow.

  

Would it be improved by somehow splitting into several Transactions ?

It depends. If entities have no correlation, you can parallelize them. Otherwise, because the context is not thread-safe , it can not be paralleled.

This does not mean it will be faster. Parallelization is recommended for large volumes of data. For small transactions, the difference in performance is not very felt.

Another thing you can do is to use asynchronous methods that improve competition between requests, but you will 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();
}
    
08.06.2016 / 22:22