首页 > 解决方案 > 使用异步 API 调用好不好?

问题描述

我想知道下面的代码在等待异步 api 调用时是否执行下一条语句?如果是这样,那么该值将为 null 并可能导致 null 异常?我这样做正确吗?

var response = await pl_httpClient.GetAsync("api/GetInfo?CardNo=" + CardNo);

if (!response.IsSuccessStatusCode) 
{ 
return response.StatusCode); 
}

InfoModel infoModel = await response.Content.ReadAsAsync<InfoModel>();

if(infoModel == null){ return "Card number is invalid"; }

if (infoModel.ExpiryDate < DateTime.Now.Date) { return "Expired Card Number"; }

if (!infoModel.MemberStatus.Equals("1")) { return "Inactive Card Number"; }

标签: c#apiasynchronoushttpclient

解决方案


我喜欢考虑它的方式是await暂停方法而不是线程。所以对于这样的代码:

var response = await pl_httpClient.GetAsync("api/GetInfo?CardNo=" + CardNo);
if (!response.IsSuccessStatusCode) 

整个方法在该await语句处暂停,直到下载完成。然后该方法继续执行,设置response变量,然后继续检查response.IsSuccessStatusCode


推荐阅读