c# - 使用异步 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"; }
解决方案
我喜欢考虑它的方式是await
暂停方法而不是线程。所以对于这样的代码:
var response = await pl_httpClient.GetAsync("api/GetInfo?CardNo=" + CardNo);
if (!response.IsSuccessStatusCode)
整个方法在该await
语句处暂停,直到下载完成。然后该方法继续执行,设置response
变量,然后继续检查response.IsSuccessStatusCode
。
推荐阅读
- c# - 如何将项目添加到列表的末尾,中间有空项目?
- python - 在 Pandas 中获取每两行不同的新数据框
- java - 存储为字符类型的数组列表的大数的乘法
- c++builder - 捕获多播视频
- python - 重塑图像以适应 SVM 分类器
- javascript - 如何解密已经加密的答案
- javascript - CKEditor5 设置'无法读取未定义的属性'创建''
- ruby-on-rails - 为 rspec 添加别名以便于调用 pry
- json - 尝试创建地图但以 JQ 中的 List 结尾
- python-3.x - 为 Python3 设置 SublimeText……这个命令有什么作用?