Friday, September 28, 2018

The simple purpose of C# 's async & await

Async/Await has one single goal, to write asynchronous callbacks in a way that looks like normal everyday easy to read code.

Here is an example of retrieving a string response asynchronously using callbacks,

Compare this with the awaited version,

While the callback version is reasonably simple, if you continue to add more and more asynchronous calls nested inside each callback, you reach a point called "callback hell" where the code is very hard to track. Let's try where we want to do 3 asynchronous calls, in order, to retrieve 3 website's content.

Now compare this to the awaited version,

Very quickly we see why await can be so much easier for humans to read and understand; it looks like normal sequential code with no callbacks required. There isn't much more to it than this, and for the majority of developers this is all you need to know to get started.

No comments: