What are the performance implications of BeginTransaction() vs BeginTransactionAsync()

Viewed 4205

I have an implementation of an atomic transaction in which many contexts are being updated inside an asynchronous HTTP POST method.

Before the transaction implementation, I was manipulating my contexts asynchronously eg (await _context.Foo.AddAsync(trade); await _context.SaveChangesAsync();)

After understanding the need for transitions and seen many synchronous examples out there I decided to implement them synchronously:

using (var transaction = _context.Database.BeginTransaction())
            {
                //_context.Database.Log = Console.WriteLine();

                try
                {
                    _context.Foo.Add(foo);
                    _context.SaveChanges();

                    _context.TradeItems.AddRange(new List<Bar>{});
                    _context.SaveChanges();
                    
                    transaction.Commit();

Since atomicity is a priority to me, I am OK doing it this way.

However, should I do it async instead? What are the performance implications of BeginTransaction() vs BeginTransactionAsync()

1 Answers

Asynchronous function versions are introduced for reusing threads which are "waiting" for operation completion. If your application has a lot of simultaneous requests - asynchronous calls is a benefit.

If you really care about performance and server resources, rewrite your code to use asynchronous versions. And do not call SaveChanges after each operation.

using (var transaction = await _context.Database.BeginTransactionAsync())
{
    try
    {
        _context.Foo.Add(foo);
        _context.TradeItems.AddRange(new List<Bar>{});

        await _context.SaveChangesAsync();
        
        await transaction.CommitAsync();
    }

AddAsync is needed only of you have special value generation in your entities which needs Database request.

Related