如何在asp web api的第二次异步调用中等待异步结果

本文关键字:异步 调用 等待 结果 第二次 asp web api | 更新日期: 2023-09-27 18:01:37

我必须使用第一次异步调用的结果来调用第二个异步方法,但web api在完成调用方法2之前返回空结果?

我已经尝试使用。continuewith,但出现死锁

谁能给我一个解决办法吗?

的例子:

public class AsyncApiController : ApiController
{
    [ActionName("GetClientBySSN")]
    public async Task<IHttpActionResult> GetClientBySSN(string ssn)
    {
        return Ok(await _repository.GetClientBySSN(ssn));
    }
}
public interface IResRepository
{
    Task<ClientResponse> GetClientBySSN(string ssn);
}
public class ResRepository : IResRepository
{
    public Task<ClientResponse> GetClientBySSN(string ssn)
    {
        //async method
        Task task1 = _service.GetClientNumberBySSN(ssn);
        int clientNumber = task1.Result.clientnumber;
        if (clientNumber != null)
        {
            //another async method that uses ID from the first result
            return _service.GetClientDetailsByClientNumber(clientNumber);
        }
        else
        {
            return null;
        }
    }
}

如何在asp web api的第二次异步调用中等待异步结果

您需要将async添加到您的方法签名中,然后在您的方法调用中添加await关键字。

我标记了您需要更改代码的地方以及代码没有多大意义的地方,例如检查int实例是否为null(您的if语句)。

public class ResRepository : IResRepository
{
    // missing async
    public async Task<ClientResponse> GetClientBySSN(string ssn)
    {
        // missing await - also use await and get result directly instead of getting the task and then awaiting it
        var client = await _service.GetClientNumberBySSN(ssn);
        // type int can never be null, this will never eval to false. maybe you meant int? above
        // I changed to to client null check instead, maybe that is what you were going for
        if (client != null)
        {
            //another async method that uses ID from the first result
            // change - missing await
            return await _service.GetClientDetailsByClientNumber(client.clientNumber);
        }
        else
        {
            return null;
        }
    }
}

另外,使用后缀Async来命名使用await/async的方法也是很好的做法。所以GetClientDetailsByClientNumber变成了GetClientDetailsByClientNumberAsync GetClientBySSN变成了GetClientBySSNAsync。这使得代码的实现细节对调用者更清晰。

如果您使用的是web api或更一般的网络应用程序服务,请区分客户端和服务器端。

首先,你不需要async api来使你的客户端异步:双方是完全独立的。所以,我最初的建议是,你可能只想让客户端异步,并在服务器上维护web api作为同步调用(当然,可以有一个应用程序主机框架负责实例化调用,负载平衡等)。

第二点与异步api的影响有关,这意味着客户端基础设施应该收到请求完成的通知,因此必须在客户端打开一个接收此类通知的通道,并且在此接口的设计过程中不可能完全明显。所以,除非有明确的、不同的架构要求,否则我还是会选择客户端异步版本的接口。

最后一点,回到你的问题,如果你刚刚用经典的async - await修复了你的代码…

99%的情况下,await Foo()应该是await Foo().ConfigureAwait(false)

你的情况似乎落在上下文无关的情况