Published: Wednesday 6 May 2020
Anyone who has programmed in C# has probably come across keywords such as async or await. And, you may have also come across the Task class. These help you program your C# application. But is there any real benefits using asynchronous in a ASP.NET Core app?
It's probably a good time to describe what synchronous and asynchronous is and how the two differ. There are quite a lot of differences between the two.
I've taken the example of a fast food restaurant. Below shows a customer requesting their order to the assistant.
So that same assistant goes ahead and prepares their burger. Once the burger is ready, the assistant gives it to the customer. But hold on, the customer also wants a portion of fries.
So the same assistant goes ahead and prepares their fries. Whilst all this is happening, the line is getting longer and other customers are starting to get impatient.
Finally, the customer has all his food items and can go away and thrust their hunger. But now there are three other customers that have joined the line.
That's basically synchronous in a nutshell.
As you can see, this is simple approach, but quite time consuming. A queue can be formed for intensive tasks. Now, that's look at the alternative.
Once again, I've taken the example of a fast-food restaurant. The same customer is requesting their order to the assistant.
But rather than the same assistant preparing the order, they delegate the order to their co-workers. And if the customer requests to add to their order, that can also be delegated.
That means that the assistant can serve the next customer whilst the previous customer's order is being prepared. Once the order is ready, the assistant's co-workers can deliver the food to the customer.
That's basically asynchronous in a nutshell.
So, we can see some obviously speed advantages with asynchronous. However, there may be a case that there is too much going on for the system to cope.
There are some applications where asynchronous is a good approach, such as a desktop application. But what about web applications? Web servers are designed to work asynchronously. If you load a page and open up your browser's developer tools, you will see that the images and style sheets run in parallel, creating new threads every time. They don't wait to load one at the time, otherwise you would be there forever.
I've put together a little test to see if that's the case. We throw a number of requests at synchronous and asynchronous methods to see which one performs the quickest. Watch the video below to find out the results.
But, it's worth noting to review what parts of your application you are making asynchronous and how it will effect performance. It's not just the case of changing the return type to Task and adding async and await all over your application. Seeking extra performance this way may have the opposite effect!