Open Closed

Different threads concurrently using the same instance of DbContext #10627

kfrancis created
  • What is your product version? v10.5.0
  • What is your product type (Angular or MVC)? MVC
  • What is product framework type (.net framework or .net core)? Net5.0

We've been experiencing some growing pains here and on watching a really informative webinar yesterday ( we've tried to start working on some of those anti-patterns we were using (like awaits inside loops).

Now that we've started, however, we're getting the error:

A second operation was started on this context before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext

Here's one such example, the original code:

The modified code:

What are we missing here? We can wrap things in semaphoneslim to correct this (since lock can't have async code inside) but that doesn't "smell" right at all ..

1 Answer(s)
  • 0
    musa.demir created
    Support Team

    Hi @kfrancis

    Currently efcore does not support multiple parallel operations being run on the same DbContext. See:

    When you use IRepository, aspnetboilerplate's manages all dbcontext creations according to tenant and it's connection strings. The existing implementation stores created dbcontext and returns it when it is requested. See:

    And here is where dbcontext created:

    That's why running multiple parallel operations on db queries is not supported right now. You may override related part of the codes and return new dbcontext for each requests of the IDbContextProvider. That would solve the problem.