.NET Async Programming in a Nutshell
--
Asynchronous programming is not a new concept and has been around for several years and it is nowadays a new standard in modern frameworks like AspNetCore. This framework is now fully asynchronous and it's not easy to avoid using its async keyword.
I think there is a certain cloud of fear when it comes to asynchronism, developers sometimes feel afraid of using it because they don’t understand how to use it and its best practices.
Another reason for this sense of fear is due to the fact that in the past asynchronous programming was not easy at all indeed. Since the introduction of async/await keywords in C# 5 asynchronous programming has become much easier to work with.
If you are afraid of asynchronism you have come to the right place, there is no need to jump up to me! In this article, I’ll present you with some of the best practices when it comes to async programming in .NET and you’ll see that's not that big of a deal you might think it is.
What is Asynchronous Programming?
“Asynchronous programming is a means of parallel programming in which a unit of work runs separately from the main application thread and notifies the calling thread of its completion, failure or progress.” — Source
The core of asynchronous programming are theTask
objects, which model asynchronous operations. They are supported by the async
and await
keywords.
The await keyword is where the magic happens. It yields control to the caller of the method that performed await, and it ultimately allows a service to be elastic.
Async all the way
When using asynchronous programming you should use it all the way, this means that all your callers should be async. The effort in asynchronous programming can be worthless if you don’t apply it all the way in your code.
In some cases partially asynchronism can outcome worst results that fully synchronous programming, therefore my advice is to go asynchronous all over your entire stack.