Reputation: 3072
I’ve overridden the SaveChangesAsync
method of my DbContext
to call a bunch stored procedure. First I call the SaveChangesAsync
of DbContext
, after that I execute a stored procedure for each changed entity.
All async method calls are awaited.
This is the exception thrown by EF:
System.NotSupportedException: A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.
at System.Data.Entity.Internal.ThrowingMonitor.EnsureNotEntered()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreCommandAsync(TransactionalBehavior transactionalBehavior, String commandText, CancellationToken cancellationToken, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlCommandAsync(TransactionalBehavior transactionalBehavior, String sql, CancellationToken cancellationToken, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommandAsync(TransactionalBehavior transactionalBehavior, String sql, CancellationToken cancellationToken, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommandAsync(String sql, CancellationToken cancellationToken, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommandAsync(String sql, Object[] parameters)
at Common.Dal.AuditDbContext.<>c__DisplayClass20_0.<WriteAuditsParallelAsync>b__0(Audit x) in
at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
at System.Threading.Tasks.Task.WhenAll[TResult](IEnumerable`1 tasks)
at Common.Dal.AuditDbContext.<WriteAuditsParallelAsync>d__20.MoveNext() in
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Common.Dal.AuditDbContext.<SaveToDatabaseAsync>d__18.MoveNext() in
This is my code:
public override Task<Int32> SaveChangesAsync( CancellationToken cancellationToken )
{
var modified = this.GetModifiedOrDeletedEntities();
var added = this.GetAddedEntities();
var audits = AuditService.GetAudits( GetObjectStateManager(), modified );
//Call SaveChangesAsync
var result = await base.SaveChangesAsync( cancellationToken );
audits.AddRange( AuditService.GetAudits( GetObjectStateManager(), added ) );
//Call stored prcedures
await WriteAuditsAsync( audits, user );
return result;
}
private async Task WriteAuditsAsync(List<Audit> audits, String user)
{
foreach ( var audit in audits)
{
try
{
...
//Execute SQL command
await Database.ExecuteSqlCommandAsync(myCommand, myParameters);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
Why is EF throwing this exception?
Upvotes: 3
Views: 2026
Reputation: 116548
Looking at the exception you can see that you're calling Task.WhenAll
in WriteAuditsParallelAsync
which means you're starting multiple asynchronous operations at the same time and you asynchronously wait for all of them to complete.
You can't execute more than single operation concurrently on an EF context, and that's why it throws.
You can fix that by executing these operations sequentially by starting and awaiting them one at a time.
Upvotes: 3