Implementing an asynchronous controller action method

Now, we are going to change the implementation of the unanswered questions endpoint so that it's asynchronous:

  1. We are going to start by creating an asynchronous version of the data repository method that gets unanswered questions. So, let's create a new method in the data repository interface:
public interface IDataRepository
{
...
IEnumerable<QuestionGetManyResponse>
GetUnansweredQuestions();
Task<IEnumerable<QuestionGetManyResponse>>
GetUnansweredQuestionsAsync();

...
}

A key difference of an asynchronous method is that it returns a Task of the type that will eventually be returned.

  1. Let's create the data repository method implementation:
public async Task<IEnumerable<QuestionGetManyResponse>> 
GetUnansweredQuestionsAsync()
{
using (var connection = new SqlConnection(_connectionString))
{
await connection.OpenAsync();
return await
connection.QueryAsync<QuestionGetManyResponse>(
"EXEC dbo.Question_GetUnanswered");
}
}

The async keyword before the return type signifies that the method is asynchronous. The implementation is very similar to the synchronous version, except that we use the asynchronous Dapper version of opening the connection and executing the query with the await keyword. 

When making code asynchronous, all the I/O calls in the calling stack must be asynchronous. If any I/O call is synchronous, then the thread will be blocked rather than returning to the thread pool and so threads won't be managed efficiently.
  1. Let's change the API controller action method:
[HttpGet("unanswered")]
public async Task<IEnumerable<QuestionGetManyResponse>>
GetUnansweredQuestions()
{
return await _dataRepository.GetUnansweredQuestionsAsync();
}

We mark the method as asynchronous with the async keyword and return a Task of the type we eventually want to return. We also call the asynchronous version of the data repository method with the await keyword.

Our unanswered questions endpoint is now asynchronous.

  1. Start the REST API running by pressing F5 in Visual Studio.
  2. Let's load test this in WebSurge with the same configuration we used to test the synchronous implementation. Start the load test.
  3. When the REST API is struggling or we are toward the end of the duration, switch to Visual Studio and pause the REST API by pressing Ctrl + Alt + Break and then look at the Threads window by pressing Ctrl Alt H. We'll see that only a few threads are being used:

This shows that asynchronous code uses the web server's resources more efficiently under load. When writing asynchronous code, it is really important that all the I/O calls are asynchronous; otherwise, the code will behave as synchronous code, thus using the thread pool inefficiently.

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

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