使用异步API调用是否合适?

问题描述 投票:0回答:2

我想知道下面的代码是否在等待异步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# api asynchronous httpclient
2个回答
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


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";
}
© www.soinside.com 2019 - 2024. All rights reserved.