Kontext Kontext

InvalidOperationException: A second operation was started on this context instance before a previous operation completed

event 2023-09-05 visibility 4,783 comment 0 insights toc
more_vert
insights Stats

When using Entity Framework in .NET Core, we may encounter the following error:

InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently 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.
Microsoft.EntityFrameworkCore.Infrastructure.Internal.ConcurrencyDetector.EnterCriticalSection()

Root cause

The exception was thrown out because Entity Framework Core does not support multiple parallel operations on the same DbContext instance. To address this problem, we need to check if we are running parallel operations on the same DbContext and also to ensure we use await to ensure the asynchronous operation is completed.


For my scenario, it is simply because I forgot to add await for the Async method.

_ = dbContext.AddEventAsync(EventType.ModifyContent, result.Model.Title, result.Model.Path, contentId: Input.Id, siteId: result.Model.SiteId);                logger.LogInformation(stringLocalizer["Edit content: {0}; ID: {1}"], Input.Title, Input.Id);

Fix the problem

To address the problem, adding await to the above line fixes the problem:

_ = await dbContext.AddEventAsync(EventType.ModifyContent, result.Model.Title, result.Model.Path, contentId: Input.Id, siteId: result.Model.SiteId);                logger.LogInformation(stringLocalizer["Edit content: {0}; ID: {1}"], Input.Title, Input.Id);


DbContext is not thread safe

In EntityFramework Core, DbContext is not thread safe, hence we should always create a new instance of DbContext in each thread. We should not share DbContext in parallel programming.


More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts