Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous commit in entity framework?

How do I commit transaction asynchronously in entity framework?

using (var transaction = this.db.Database.BeginTransaction())
{
    this.db.DoSomething();
    await this.db.SaveChangesAsync().ConfigureAwait(false);

    // note .Commit isn't async but it involves network i/o
    transaction.Commit();
}

I'd like to make .Commit asynchronous, but I don't see appropriate API in DbContextTransaction

like image 246
psla Avatar asked May 19 '17 17:05

psla


People also ask

Should I use async EF core?

Generally speaking, if there are asynchronous APIs, then you should use them for new code. Asynchronous code frees up the calling thread. If your application is a GUI application, this can free up the UI thread; if your application is a server application, this can free up threads to handle other requests.

Does SaveChanges commit?

In Entity Framework, the SaveChanges() method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it. Multiple SaveChanges() calls, create separate transactions, perform CRUD operations and then commit each transaction.

Why does where () not have an asynchronous counterpart?

Note that there are no async versions of some LINQ operators such as Where or OrderBy, because these only build up the LINQ expression tree and don't cause the query to be executed in the database. Only operators which cause query execution have async counterparts.

When would you use SaveChanges false AcceptAllChanges ()?

Sometimes though the SaveChanges(false) + AcceptAllChanges() pairing is useful. The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts. If context1. SaveChanges() succeeds but context2.


1 Answers

In trying to determine the same thing, I walked through the EF6 source code for DbContext.SaveChangesAsync() to see how EF handled the committing of the implicit transaction on an async call.

Concurring with Ivan's comment on your question above, there is no mechanism for async commit in EF or System.Data.

In ObjectContext.ExecuteInTransactionAsync, which is where the transaction is handled for SaveChangesAsync, the asynchronous update routine is simply wrapped in EntityConnection.BeginTransaction and the synchronous DbTransaction.Commit. If there was a little known asynchronous asynchronous Commit, I would assume it would be used here.

This seems like a gaping hole in the asynchronous offerings for System.Data since a large transaction could potentially take a long time to commit, tying up a thread in the process. A server application with heavy database update activity could potentially lose a lot of the benefit of asynchronous code because of this.

like image 142
MikeJansen Avatar answered Oct 12 '22 16:10

MikeJansen