efcore: deadlock when calling SaveChangesAsync from synchronous method

[sorry for my bad English]

Some times I have to call SaveChangesAsync from synchronous method.

In EF6 it works well. In EFCore on AspNetCore, it works well. But in EFCore on Aspnet it causes deadlock.

Context:

public class MyContext : DbContext
{
    public MyContext(DbContextOptions<MyContext> options) : base(options)
    {
    }

    public DbSet<Customer> Customers { get; set; }

    public int SaveChangesSynchronous() 
        => SaveChangesAsync()
        .ConfigureAwait(false)
        .GetAwaiter()
        .GetResult();
}

Controller action:

[HttpPost]
public Customer Post(Customer customer)
{
    context.Customers.Update(customer);
    context.SaveChangesSynchronous();
    return customer;
}

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 15 (8 by maintainers)

Most upvoted comments

@YehudahA Yes it solves our problem. We created this duplicate Ticket Deadlock in WPF when calling .Wait() #12407. Before we had deadlocks when we call .Wait() on an async operations. With the modified EFCore Version RZL.ConfigureAwaitAnalyzer it works in all cases. It is easy to test it with our Sample Project.

Please add ConfigureAwait(false) in the EFCore Library. We are porting our EF6 WPF application to EFCore. Most of our queries and business logic code are written in async. We are reusing same methods multiple times. In some cases we need to call .Wait() for these methods (for example the user is not allowed to change the row in a datagrid -> DB-Queries to check). In EF6 we had no problems at all. Now in EFCore we have a lot of deadlocks. Our rule is, no await without ConfigureAwait(false) in our Domain/Library Assemblies --> we have written an roslyn analyzer to guarantee this. If EFCore do not fix this important issue, we need to create our own branch and fix it ourselves.

@YehudahA We uploaded our Roslyn analyzer, that ensures that all await calls are configured with .ConfigureAwait(false): RZL.ConfigureAwaitAnalyzer

We forked EntityFrameworkCore and branched from 2.1.1 where we added .ConfigureAwait(false) to all await calls: ConfigureAwait Branch The analyzer is not yet added to our branch, because we haven“t published it to Nuget yet.