Kate Lastimosa
Kate Lastimosa

Reputation: 189

Is it good to use asynchronous API calls?

I want to know if the code below executes the next statement while waiting for the async API call? If so, then the value would be null and might cause a null exception? Am I doing this correctly?

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"; }

Upvotes: 0

Views: 193

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456322

The way I like to think about it is that await pauses the method but not the thread. So for code like this:

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

The entire method is paused at the await statement until the download is complete. Then the method resumes executing, sets the response variable, and then proceeds with checking response.IsSuccessStatusCode.

Upvotes: 2

Related Questions