Asynchronous Programming

Learn about asynchronous concepts. In addition, learn how to implement them into your repository interface and learn about classes that implement that interface.

Synchronous vs asynchronous

To understand asynchronous programming, you have to understand the difference between synchronous and asynchronous.

Synchronous

When starting to learn to code, the code that is written is almost always synchronous. The operations performed in your code are taking place one after another. For example, there are three tasks: Task A, B, and C. Task B will not start before Task A finishes, and Task C will not start before Task B finishes, even if all three tasks are not dependent on each other.

Asynchronous

An asynchronous operation allows tasks to be executed and completed out of order. If you have three tasks, and none of them are dependent on the other, then they can all execute simultaneously, and one task may complete before the other.

Asynchronous in ASP.NET

Multiple users access a web application at the same time. If you have a server with enough processing power (enough threads in the thread pool for each user), it might be able to handle all user requests simultaneously. However, this is not the most efficient way. It also does not scale well, as the number of users and application scope increase. By implementing asynchronous functionality, one thread can take a user’s request, perform some processing on it, transfer it to the database for I/O operations and not wait for the database to return a result but instead move to the next user’s request. When the database has completed the I/O operations, it returns the result to whichever thread is available. That thread then returns the result to the appropriate user.

Implementation

When you scaffolded controllers in the previous lessons from MVC and JSON chapters, the framework implemented asynchronous operations for you. However, when you have to write action methods yourself, you have to incorporate asynchronous keywords to allow those methods to execute asynchronously. Hence, you will revisit your repository classes and update them to support asynchronous operations.

IUserRepo.cs

If a function returns an object of type User and you want to convert it into an asynchronous function, we need to change its return type to Task<User>. This is done to allow asynchronous behaviors in the action method. This is what your repository interface will look like as a result of the changes:

Get hands-on with 1200+ tech skills courses.