首页 > 解决方案 > web.api 中的同步和异步方法

问题描述

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

    [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..

标签: c#asynchronousasp.net-web-apiasync-await

解决方案


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

一旦你没有在 async/await 函数中混合阻塞调用Result.Wait并且正确地等待async 函数,你应该能够同时进行 async 和 sync 调用。

参考Async/Await - 异步编程的最佳实践


推荐阅读