Understanding C# Async/Await

Back in .Net Framework 4.5, Microsoft introduced two new keywords to make asynchronous programming easy for developers.

These keywords, async & await have been first class citizens of C# since then and have helped developers easily introduce concurrency in their applications.

However, many developers are still confused about the roles these keywords play in everyday development so I’m happy to shed some light on this.

Consider the code below:

public ActionResult Pay(int customerId, int amount)
{
var customer = customerRepository.Find(customerId);
var result = processPayment(customer, amount);

FlashSuccess("Payment successfully made");
return View("PaymentSuccess");
}

This method runs synchronously and in this case on the UI thread. The drawback here is that multiple requests to this method will have to wait till the currently executing request completes and returns.

For low traffic applications, this code will work just fine but when your app begins to grow and traffic increases, users might experience some amount of lag between requests. Here’s where async/await can be of help!

Now let’s modify the code above to use the async/await keywords.

public async Task<ActionResult> Pay(int customerId, int amount)
{
var customer = customerRepository.Find(customerId);
var result = await processPayment(customer, amount);

FlashSuccess("Payment successfully made");
return View("PaymentSuccess");
}

As shown above, the async keyword is included in the method definition and the return type for the method is a generic Task. Also notice that we placed the await keyword just before the processPayment(…) method.

Now what’s going on here? Well the await keyword instructs the compiler to run the processPayment(…) method on a worker thread which it grabs from the thread pool, thus freeing up the UI thread to handle other requests. Once processPayment(…) completes, control is returned to the original thread i.e. the UI thread for the request to continue processing. Typically, methods that take long to return (calls to databases, external APIs, disk etc) are candidates for asynchronous processing.

Finally, asynchronous methods can also return void instead of a Task. This is useful when you care less about whether that method completes or not, essentially performing a fire-and-forget request. One disadvantage here is that your app won’t be notified if an error occurs.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store