【问题标题】:Synchronous and async methods in a web.apiweb.api 中的同步和异步方法
【发布时间】:2018-09-08 22:26:49
【问题描述】:

有人可以解释一下这段代码是否是潜在的死锁。 将同步数据库调用与异步数据库调用混合,如下面的代码。或者如果先执行异步调用,是否有死锁的风险。

    [Route("{id}/someobjects")]
    [ResponseType(typeof(IEnumerable<SomobjectDto>))]
    public async Task<IHttpActionResult> GetSomeobjects(string id)
    {
        var syncMethodResult = SyncDBCallMethod(); //In this method there is a databas call..

        var asyncMethodresult = await AsyncDBMCallMethod(1L);  //In this method there is a Async databas call..

【问题讨论】:

  • 在这种情况下,异步调用将在同步调用完成之前开始。一旦您没有将 Result.Wait 之类的阻塞调用与异步混合,您应该能够进行异步和同步调用。参考Async/Await - Best Practices in Asynchronous Programming
  • 认真看SyncDBCallMethod是否可以转换。如果您可以将 all 长时间运行的活动(并且始终假定数据库调用如此)作为某种形式的异步,您将获得最大的好处。

标签: c# asynchronous asp.net-web-api async-await


【解决方案1】:

在这种情况下,异步 AsyncDBMCallMethod 调用将在同步 SyncDBCallMethod 完成之前开始。

一旦您没有在 async/await 函数中混合像 Result.Wait 这样的阻塞调用,并且正确地 await 异步函数,您应该能够同时进行 async 和 sync 调用。

参考Async/Await - Best Practices in Asynchronous Programming

【讨论】:

  • 好的。谢谢你。但是同步方法会阻止三者吗?那么,与普通同步方式相比,这种半异步方式有什么意义/好处吗?
猜你喜欢
  • 2018-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多