Upgrade your butler to Async

The async and await keywords have been around for a while (since .Net 4.5) yet there still remains a fair amount of confusion regarding how it works. First off, while the compiler is arguably doing something akin to magic, you could achieve much the same results with BeginInvoke and EndInvoke. The async/await way of doing things makes the code more natural to write and reason about but there is nothing new in the operating system to make this magic.

A basic thing async/await does for you is to allow scalability by allowing your thread to go off and do other work while you wait on some asynchronous activity. It does not mean you spin up new threads and do processing in parallel (though, you could). I’ll describe this in non-technical terms to make it clear.

Suppose you have a butler and we will say he is a synchronous butler. Your butler has been tasked with folding your underwear but you decide to order pizza so you tell your butler to stop folding and go wait at the door for the delivery. Your butler is effectively blocked from doing anything while the pizza is cooked and delivered. When the doorbell rings he will open the door, pay the driver, serve your pizza then get back to folding your spiderman underoos.

What a waste. Why can’t your butler keep folding clothes while the pizza is on its way? If you got the asynchronous model he easily could. He would call to order your pizza, put the task of answering the doorbell on hold, then go do other work. When the doorbell rings, he will pick up his task of serving you pizza where he left off and get the door.

That is the very basics of async/await. When you await a task the thread is free to do other work but it will come back and finish up when it needs to. This provides scalability by not wasting threads and forcing them to sit around idle. You are allowing your application and the operating system to operate more efficiently.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s