Mixing asynchronous and synchronous code

An easy mistake to make is to mix asynchronous code with synchronous code. In fact, we have made this mistake in our PostAnswer action method because the method is synchronous but the call to the SignalR hub is asynchronous:

[HttpPost("answer")]
public ActionResult<AnswerGetResponse>
PostAnswer(AnswerPostRequest answerPostRequest)
{
...
_questionHubContext.Clients.Group(
$"Question-{answerPostRequest.QuestionId.Value}")
.SendAsync
(
"ReceiveQuestion",
_dataRepository.GetQuestion(answerPostRequest.QuestionId.Value)
);

return savedAnswer;
}

The code functions correctly but is suboptimal because not only is the thread that handles the request blocked from handling other requests, but we also have all of the overhead of handling asynchronous code.

The resolution is to make all of the code asynchronous, which includes following the same pattern that we have just followed. The code for this can be found in this book's GitHub repository at https://github.com/PacktPublishing/ASP.NET-Core-3-and-React-17 in the Chapter10 folder. In fact, all of the code has been made asynchronous in this repository.

In the next section, we are going to look at how we can optimize requests for data by caching data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.89.60