我必须使用第一个异步调用中的结果来调用第二个异步方法,但是web在调用方法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;
}
}
}
发布于 2016-08-09 18:12:15
您需要将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
后缀的等待/异步的方法命名也是很好的做法。所以GetClientDetailsByClientNumber
会变成GetClientDetailsByClientNumberAsync
,GetClientBySSN
会变成GetClientBySSNAsync
。这使调用方更清楚地了解代码的实现细节。
发布于 2016-08-09 20:26:38
如果您使用的是web api或更一般的网络应用程序服务,请区分客户端和服务器端。
首先,您不需要使用异步api来使您的客户端异步:双方完全独立。因此,我最初的建议是,您可能希望只进行客户端异步,并将web api维护为服务器上的同步调用(当然,可以有一个负责实例化调用、负载平衡等的应用程序主机框架)。
第二点与异步api的影响有关,这意味着客户端基础结构应该被通知请求完成,因此有一个接收此类通知的通道,该通知必须在客户端打开,并且在此接口的设计过程中不可能完全显而易见。因此,除非有明确、不同的体系结构需求,否则我还是会选择只使用接口的异步版本的客户机。
最后一个注意事项,回到你的问题,万一你刚刚用经典异步修复了你的代码-等待所有的方式.
99%的时间,等待Foo()应该等待Foo().ConfigureAwait(false)
你的案子似乎是在上下文无关的情况下
https://stackoverflow.com/questions/38857574
复制相似问题