I know similar questions have been asked, but I'm struggling with the concepts of asynchronous programming in .net. As a web developer, I understood how calling functions asynchronously didn't cause the UI to block and you could do other things. But now I'm on the other side, writing a C# Web API service to retrieve information from a database and do some calculations. I made the functions in the controller async by adding the async keyword to the function header, which I naively thought would be the end of it, but then it tells me I need to use the await keyword in the function. So I figured out how to do that (I have read a lot by this point) but I don't get WHY I need to do that, as well as WHEN. Like say I have a web method like below where it calls two other functions but only one is called with await. Is that bad? Will it only be non-blocking part of the time? I then made another test function that has no await keyword and it worked fine (bottom code).
[HttpPost]
public async Task<IHttpActionResult> CalculateBMIAsync([FromBody]MeasureInput patientData)
{
string results = String.Empty;
MeasureReturn returnVal = null;
try
{
string msgInvalid = await Translators.validatePatMonthXML(patientData);
if (String.IsNullOrEmpty(msgInvalid))
{
results = await measureProcessor.CalculateBMI(patientData);
}
else
return new BadRequestWithInfoResult(Translators.CreateErrorXML(new Exception(msgInvalid)));
}
catch (Exception ex)
{
return new BadRequestWithInfoResult(Translators.CreateErrorXML(ex));
}
return Ok<MeasureReturn>(returnVal);
}
Example web API method that worked asynchronously when called with jquery (no await used here):
[HttpPost]
public async Task<IHttpActionResult> CalculateTest()
{
long d = 0;
for (long i = 0; i < 2000000000; i++)
{
d = i;
}
string returnVal = d.ToString();
return Ok(returnVal);
}
Calling code:
$('#btn1').click(function () {
console.log('Ajax request');
$.ajax({
url: 'http://localhost:53312/api/Measures/CalculateTest',
type: 'POST',
success: function (data) {
$('#result1').html('async request finished');
}
})
});