我正在尝试使用resharp执行异步请求,但是'response‘总是空的,为什么?
private IRestResponse response;
public IRestResponse POSTAsync(string url) {
IRestResponse response = null;
client.ExecuteAsync(new RestRequest(url, Method.POST), (r) => {
if (r.StatusCode == HttpStatusCode.OK)
response = r;
});
return response;
}发布于 2018-08-29 03:42:11
在我看来,响应将始终为空,因为您调用的是异步服务,而不是等待事务结束。
private IRestResponse response;
public IRestResponse POSTAsync(string url) {
IRestResponse response = null;
client.ExecuteAsync(new RestRequest(url, Method.POST), (r) => {
if (r.StatusCode == HttpStatusCode.OK) // This is going to a new thread and will be executing later
response = r; // eventually this will be called, but your method did not wait for that completition
});
return response; // Response will always be null because the Async method is not
// finished yet
}因此,如果您周围的代码不支持异步方法,则不应该使用try来使用它,因为最终您将需要阻塞您的方法来等待结果。
这就是为什么创建了async关键字,您还需要使所有调用依赖于异步调用,这也是控制器现在支持async和tasks作为返回类型的原因(作为现代Net Core应用程序的示例):
[HttpGet("{msisdn}")]
public Task<string> Get(string msisdn)
{
return _hubUserProfileService.CallProfileService(msisdn);
}所以,更新你的应用程序,让你的整个请求都是异步的,或者干脆不使用它,因为它不会给你的代码带来任何东西,现在它甚至更重,因为它必须创建任务来调用其他线程中的方法……而调用方法无论如何都必须等待响应。
澄清一下:
调用异步方法并不神奇,您希望请求在另一个线程中执行,然而,在创建该线程后,您立即跳转到可用的结果,而这不是异步执行的工作方式,您的回调将在未来的某个地方执行,您不知道何时,这就是为什么需要回调方法,该方法将只创建任务并继续,但任务尚未执行,您的变量仍然为空,您可以在返回响应之前添加一个Thread.Sleep()来验证我所说的,这样您就可以为异步回调的完成留出时间。这就是为什么让它异步并不会给你带来任何新的东西。
https://stackoverflow.com/questions/52064733
复制相似问题