【问题标题】:Asynchronous commit in entity framework?实体框架中的异步提交?
【发布时间】:2017-05-19 17:51:11
【问题描述】:

如何在实体框架中异步提交事务?

using (var transaction = this.db.Database.BeginTransaction())
{
    this.db.DoSomething();
    await this.db.SaveChangesAsync().ConfigureAwait(false);

    // note .Commit isn't async but it involves network i/o
    transaction.Commit();
}

我想让 .Commit 异步,但我在 DbContextTransaction 中没有看到合适的 API

【问题讨论】:

  • 它看起来在内部它是异步实现的(或至少是事件驱动的) this.InternalDispatcher.Dispatch(transaction, (Action) ((t, c) => t.Commit()), new DbTransactionInterceptionContext(interceptionContext).WithConnection(transaction.Connection), (Action) ((i, t, c) => i.Committing(t, c) ), (Action) ((i, t, c) => i.Committed(t, c)));
  • DbContextTransaction中没有这样的API,因为底层DbTransaction中没有这样的API
  • 在 EF Core 3.0 中可用:参考:docs.microsoft.com/en-us/dotnet/api/…

标签: entity-framework transactions


【解决方案1】:

在尝试确定同一件事时,我浏览了 DbContext.SaveChangesAsync() 的 EF6 源代码,以了解 EF 如何处理异步调用中隐式事务的提交。

同意 Ivan 对上述问题的评论,EF 或 System.Data 中没有异步提交机制。

在为SaveChangesAsync 处理事务的ObjectContext.ExecuteInTransactionAsync 中,异步更新例程简单地包装在EntityConnection.BeginTransaction 和同步DbTransaction.Commit 中。如果有一个鲜为人知的异步异步Commit,我会假设它会在这里使用。

这似乎是 System.Data 的异步产品中的一个巨大漏洞,因为大型事务可能需要很长时间才能提交,从而占用了进程中的线程。因此,具有大量数据库更新活动的服务器应用程序可能会失去很多异步代码的好处。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    相关资源
    最近更新 更多