使用异步API调用好吗?

时间:2019-04-04 02:30:00

标签: c# api asynchronous httpclient

我想知道下面的代码在等待异步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"; }

2 个答案:

答案 0 :(得分:1)

我建议您阅读以下内容:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/

但是,回答您的问题后,await关键字对您的异步方法说,他可以执行任何所需的操作,并将等待结果。就那么简单。 另一方面,如果您不需要infoModel来执行代码的下几行,则只需删除await关键字即可。

例如:

Task<InfoModel> infoModelTask = await response.Content.ReadAsAsync<InfoModel>();
// Execute database operations, I/O etc...
InfoModel infoModel = await infoModelTask;
if (infoModel == null)
{
    return "Card number is invalid";
}

答案 1 :(得分:1)

I like to think about it的方式是await暂停方法,而不是线程。所以对于这样的代码:

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

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