How to Async

There are a number of best practices when it comes to Async what I’ll try and cover here are the “guidelines” than actual rules. There are exceptions to each of these guidelines. The guidelines are summarised in the table below.

Summary of Asynchronous Programming Guidelines

Name Description Exceptions
Avoid async void Prefer async Task methods over async void methods Event handlers
Async all the way Don’t mix blocking and async code Console main method
Configure context Use ConfigureAwait(false) when you can Methods that require con­text

Simple Asynchronous

If you have a method that is Synchronis and you can make it Asynchronous how do you do that?

With all Async calls, you have to return something back, here is a simple example where you don’t need.

Task.Run should be avoided on ASP.NET. This approach would remove all benefits from async/await and actually perform worse under load than just a synchronous call.

 public async Task<string> DeleteMessage()
            await Task.Run(() => DeleteMessages());
            return string.Empty;

If you do need to return something then it is just as easy

public async Task<string> GetFromQueue()
            var message = await Task.Run(() => GetMessage());
            return message.Body.ToString();