DEV Community

Cover image for Understanding Async and Await
Alex Hyett
Alex Hyett

Posted on • Originally published at alexhyett.com on

Understanding Async and Await

I have been doing a lot of interviews recently for backend C# developers. One question that a lot of developers get wrong is:

Can you describe the purpose of the async and await keywords?

It seems like a fairly straight forward question. Most developers explain that it stops your code from blocking the main thread which is correct, however they then go on to talk about multi-threading, which is where their understanding tends to fall apart.

Asynchronous code is not the same as multi-threading. Running something async doesn't necessarily mean that a new thread is going to be spun up.

Let's say for example you have an API that when called kicks off a slightly longer operation. This could be saving a file, writing to a database or calling another API for example.

If your API doesn't use async and await then the main thread is blocked waiting for this operation to complete. This doesn't mean that your API will be completely unresponsive until the task is complete, instead it will have to use another thread to handle the next request.

Keep this up and your application will run out of threads it can use, and your application will be unresponsive.

When you use async and await you are setting up a callback for the rest of the work. You are telling the application that you are going to be waiting a while so you might as well do something useful, and I will tell you when I am ready to continue. The thread is now free to do other work like process other requests until whatever you are awaiting is finished.

This only really works when you are waiting on something outside your application to complete. If you are doing a big calculation it is going to need to use the thread to make the calculation.

Synchronous vs Asynchronous Restaurant #

A good analogy is imagining waiters in a restaurant. Let's imagine what a synchronous restaurant looks like.

You walk into an empty restaurant that only has 1 waiter. The waiter greets you at the door, shows you to your seats and hands you a menu. You say thank you and sit down and start looking at the menu.

This is where you start to feel uneasy. The waiter is just standing there, grinning, waiting for you to pick what you want to eat and drink. There are other people showing up now, it is lunchtime after all, but still the waiter stands there grinning like a Cheshire cat.

You pick what you want from the menu and the waiter goes off to hand the details to the chef. More people show up to the restaurant and the queue is getting quite long now. You look round to see what the waiter is doing, and he is just standing waiting for the chef to cook your food.

Naturally some of the people waiting in the queue get impatient and leave.

When your food is finally done, the chef brings you your meal and then proceeds to stand there watching you eat it.

In this case the waiter is a single thread in your application that is getting blocked waiting for you to make your decision, for the chef to cook your meal and finally for you to eat it.

Meanwhile, the number of requests (customers) to your application (restaurant) is building up and many of them end up timing out and leaving.

You can imagine that if you have a few more waiters than you can serve some more customers, but you are going to run out of waiters pretty quickly.

With the asynchronous restaurant, the waiter shows you to your seat and then awaits for you to decide what you want. He is now free to go off and show some more people to their seats and await their response. Once you have picked, the waiter shows up and takes your order and then awaits for the chef to cook your meal, again freeing him up to take orders or seat other customers.

There is still only one waiter (thread) but he is able to serve many more customers (requests) because he is not waiting on blocking operations.

If you have multiple waiters then you can seat and serve multiple customers at the same time, this would be your multi-threading example.


❤️ Picks of the Week #

📝 ArticleNext-level frosted glass with backdrop-filter — Josh always writes amazing tutorials and this is no different. The frosted glass effect shown at the end is really cool.

📝 ArticleMy second year without a job — I have tried in the past to quit my job and go the entrepreneurial route. It is a tough road to walk even when you start with a big runway. It is interesting reading other people's experiences.

🛠️ ResourcesPostgres for everything (e/Postgres) — They say that if all you have is a hammer than everything looks like a nail. I wouldn't recommend building everything with Postgres but maybe if you are working on small personal project it wouldn't be so bad.

🛠️ ToolMise: Dev tools, env vars, task runner — This looks quite interesting. Trying to manage node and python without using virtual environments is a mess. Each has their own way of managing virtual environments and this looks like a great way to simplify things.

🗿 AI 3D ModellingBlenderGPT & Trellis — Creating AI generated images is useful but the chances of your getting exactly what you want is difficult. It also doesn't help much with things like games where you need 3D models. These projects will likely change the way games will be made in the future.

💬 ForumThose making $500/month on side projects in 2024 — The entrepreneur in me always loves seeing how other people are able to make money online. There are some interesting projects in here that might inspire you to create something yourself.

📝 ArticleDigital consumption keeps me from getting better at my job — It is quite terrifying if you add up all the time spent on social media that could have been spent getting better at a craft. Yes you could learn something to get better at your job but equally it could be time spent learning an instrument or spending quality time with your family.

Top comments (0)