Iterations within Transactionscope

Asked

Viewed 151 times

3

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

What are the losses caused by a TransactionScope very long?

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();
}

It would be improved in some way by dividing into several Transactions?

1 answer

2


What are the losses caused by a TransactionScope very long?

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

It would be improved somehow by dividing into several Transactions?

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

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

Another thing you can do is use asynchronous methods, which improve the competition between requests, but you will have to go to the . 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();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.