Skip to main content
 首页 » 编程设计

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

2024年04月18日38artech

我必须使用第一个异步调用中的结果来调用第二个异步方法,但 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; 
        } 
    } 
} 

请您参考如下方法:

您需要将 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。这使得调用者更清楚代码的实现细节。