3
我重写了我的DbContext
的SaveChangesAsync
方法来调用一堆存储过程。首先我打电话SaveChangesAsync
DbContext
,之后我为每个更改的实体执行一个存储过程。EF 6 - 在SaveChangesAsync方法中执行SQL命令的异步抛出NotSupportedException
所有的异步方法调用都在等待。
这是异常的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
这是我的代码:
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);
}
}
}
为什么EF抛出此异常?
你还在等待'SaveChangesAsync'和'WriteAuditsAsync'吗? – Default
'WriteAuditsParallelAsync'看起来可疑 - 您确定您正在将调用同步到数据库吗? – Default
是的,我会等待SaveChangesAsync和WriteAuditsAsync(用于WriteAuditsAsync请参阅代码) – musium