A second operation started on this context before a previous operation completed
Hi, not sure if this is something I have set up wrong, but I'm trying to test Elsa with the dashboard and designer and have used SQL Server as the EF provider. After successfully adding a couple of workflows I now get the 'second operation' error when trying to view the workflows list. Here's the stack trace:
System.AggregateException: One or more errors occurred. (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.)
---> 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.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
at Elsa.Persistence.EntityFrameworkCore.Services.EntityFrameworkCoreWorkflowInstanceStore.ListByDefinitionAsync(String definitionId, CancellationToken cancellationToken)
at Elsa.Extensions.AsyncEnumerableExtensions.ToListAsync[T](Task`1 task)
at Elsa.Dashboard.Areas.Elsa.Controllers.WorkflowDefinitionController.CreateWorkflowDefinitionListItemModelAsync(WorkflowDefinitionVersion workflowDefinition, CancellationToken cancellationToken)
at Elsa.Dashboard.Areas.Elsa.Controllers.WorkflowDefinitionController.<>c__DisplayClass7_0.<<Index>b__0>d.MoveNext()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at Elsa.Dashboard.Areas.Elsa.Controllers.WorkflowDefinitionController.<>c.<Index>b__7_1(Task`1 x)
at System.Linq.Enumerable.SelectListIterator`2.MoveNext()
at System.Linq.Lookup`2.Create(IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer)
at System.Linq.GroupedEnumerable`2.ToList()
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Elsa.Dashboard.Areas.Elsa.Controllers.WorkflowDefinitionController.Index(CancellationToken cancellationToken)
at lambda_method(Closure , Object )
at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Builder.Extensions.MapMiddleware.Invoke(HttpContext context)
at Elsa.Activities.Http.Middleware.RequestHandlerMiddleware`1.InvokeAsync(HttpContext httpContext, THandler handler)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
I've stepped through the WorkflowDefinitionController.Index task and this line run's okay:
var workflows = await workflowDefinitionStore.ListAsync(
VersionOptions.LatestOrPublished,
cancellationToken
);
but then it errors out on the subsequent call:
var workflowModelTasks = workflows.Select(
async x => await CreateWorkflowDefinitionListItemModelAsync(x, cancellationToken)
)
.ToList();
Which, as you can see from the stack trace is getting as far as EntityFrameworkCoreWorkflowInstanceStore.ListByDefinitionAsync for the next call to the dbContext which throws the error.
Has anyone got any thoughts on what's causing this?
I just tried this with the latest version from the master branch (0fbb47ff8fa232322238f6f18f86f372f8e3a496), but I'm unable to reproduce the issue. Here's what I did:
- Update
Elsa.Dashboard.Webto use EF with Sqlite. - Create 5 workflows using the dashboard.
Couple of questions:
- Which version are you using?
- Are you using Sqlite, SQL Server, or something else?
Hi Sipke, thanks for looking at this. I can confirm that it works fine for me with Sqlite, but I'm trying to use SQL Server. This is with the latest build on master, and also if I create a separate project and add the current Elsa packages (v1.1.4.2). I'm using a local SQL Server Express v14.0.2027
If it helps here's my Startup class:
public class Startup
{
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
private IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services) {
var migrationAssembly = typeof(ElsaContext).Assembly.FullName;
services
.AddElsa(elsa =>
elsa.AddEntityFrameworkStores(options =>
options.UseSqlServer(Configuration.GetConnectionString("SqlServer"),
s => s.MigrationsAssembly(migrationAssembly))))
.AddHttpActivities(options => options.Bind(Configuration.GetSection("Elsa:Http")))
.AddEmailActivities(options => options.Bind(Configuration.GetSection("Elsa:Smtp")))
.AddTimerActivities(options => options.Bind(Configuration.GetSection("Elsa:Timers")))
.AddElsaDashboard();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app
.UseStaticFiles()
.UseHttpActivities()
.UseRouting()
.UseEndpoints(endpoints => endpoints.MapControllers())
.UseWelcomePage();
}
}
Hi Martin,
I was able to reproduce the issue with SqlServer. For some reason, the following code appears to run in parallel instead of sequentially:
var workflowModelTasks = workflows.Select(async x => await CreateWorkflowDefinitionListItemModelAsync(x, cancellationToken));
I would have expected that statement would basically iterate over each workflow in the list, async/awaiting each creation of a model object, like so:
var workflowModels = new List<WorkflowDefinitionListItemModel>();
foreach (var workflow in workflows)
{
var workflowModel = await CreateWorkflowDefinitionListItemModelAsync(workflow, cancellationToken);
workflowModels.Add(workflowModel);
}
The above works. Clearly I'm not understanding something correctly, but I committed the "explicit" for each loop to develop and will merge it to master.
Great, thanks Sipke.