Efcore: [BUG] A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext.

Created on 7 Aug 2020  路  2Comments  路  Source: dotnet/efcore

I am using ef core 3.1.5 and asp.net core 3.1 and am having this constant issue around a function that sets a view bag in the edit and create methods.

Strange thing is this only happens in production on the hosted server, i dont get this error locally

``` C#
services.AddDbContext
(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Scoped);

    public async Task<int> GetNotificationsCount() {
        var userId =  GetCurrentTennantId().Result;
        //the not should show all the notifcations should only check the desnitation user id
        return _context.Notifications.Where(w => w.SharedTo == userId.ToString()).Count();
    }

```

This setup view bag would be called on functions like edit and create

 public async void SetupViewBags() {
 ViewBag.NotificationCount = await GetNotificationsCount();

   }

For Example I would call it as such

  // GET: MISObjects/Create
    public IActionResult Create() {
        SetupViewBags();

        return View();
    }

Got Exceptions? Include both the message and the stack trace

info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 165.3482ms 200 application/javascript
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (1ms) [Parameters=[@__ToString_0='?' (Size = 450)], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*)
FROM [MISobject] AS [m]
WHERE (([m].[OIC_1] = @__ToString_0) OR ([m].[OIC_2] = @__ToString_0)) AND (([m].[isDeleted] = CAST(0 AS bit)) AND ([m].[isActive] = CAST(1 AS bit)))
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 163.0282ms 200 application/javascript
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [a].[FirstName], [a].[LastName], [a].[Id]
FROM [AspNetUsers] AS [a]
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [a].[Id], [a].[AccessFailedCount], [a].[ConcurrencyStamp], [a].[Email], [a].[EmailConfirmed], [a].[FirstName], [a].[LastName], [a].[LockoutEnabled], [a].[LockoutEnd], [a].[NormalizedEmail], [a].[NormalizedUserName], [a].[PasswordHash], [a].[PhoneNumber], [a].[PhoneNumberConfirmed], [a].[SecurityStamp], [a].[TennantId], [a].[TwoFactorEnabled], [a].[UserName]
FROM [AspNetUsers] AS [a]
fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred while iterating over the results of a query for context type 'MISSystem.Dal.MISDBContext'.
System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.AsyncEnumerator.MoveNextAsync() System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913. at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection() at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.AsyncEnumerator.MoveNextAsync()
info: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[2]
Sending file. Request path: '/font-awesome/js/all.js'. Physical path: 'D:\GitMaster\MIS\uno\MISSystem.WEB\MISSystem.Web\MISSystem.Web\wwwroot\font-awesome\jsall.js'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]

For dotnet ef and PMC, share the --verbose output
An exception occurred while iterating over the results of a query for context type 'MISSystem.Dal.MISDBContext'.
System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext() System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913. at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection() at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext()
Unhandled exception. System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable1.Enumerator.MoveNext() at System.Linq.Enumerable.Single[TSource](IEnumerable1 source)
at lambda_method(Closure , QueryContext )
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteTResult
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteTResult
at System.Linq.Queryable.CountTSource
at System.Threading.QueueUserWorkItemCallback.Execute()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

Further technical details

EF Core version:
Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer)
Target framework: (e.g. .NET Core 3.0)
Operating system:
IDE: (e.g. Visual Studio 2019 16.3)

closed-question customer-reported

Most helpful comment

You are not correctly using async/await.
To fix your issues:

Change the SetupViewBags signature from async void to async Task.

Then in your controller, properly await it and change the controller action signature as following:

public async Task<IActionResult> Create() 
{
   await SetupViewBags();
   return View();
}

Furthermore you should not block in GetNotificationsCount. Use await and don't use .Result:

var userId = await GetCurrentTennantId();
return await _context.Notifications.Where(w => w.SharedTo == userId.ToString()).CountAsync();

Check your other code for these patterns and fix accordingly.

All 2 comments

You are not correctly using async/await.
To fix your issues:

Change the SetupViewBags signature from async void to async Task.

Then in your controller, properly await it and change the controller action signature as following:

public async Task<IActionResult> Create() 
{
   await SetupViewBags();
   return View();
}

Furthermore you should not block in GetNotificationsCount. Use await and don't use .Result:

var userId = await GetCurrentTennantId();
return await _context.Notifications.Where(w => w.SharedTo == userId.ToString()).CountAsync();

Check your other code for these patterns and fix accordingly.

I had the same error using ef-core in wpf with autofact. if using Ctor injection in wpf the issue seems to go away if I inject a Func in the constructor rather than injecting repository

Was this page helpful?
0 / 5 - 0 ratings