This week I had the honor to give a training to some of the newly started young professionals in our organisation. The topic of the training was API design in ASP.NET Core. During this training we discussed multiple topics and a lot of interesting questions were raised. I'll try to tackle some of them with a blog post.
The question I try to tackle today is...
Why should I make my action methods asynchronous?
I asked the question during the training why the second example is better than the first example:
Example 1 – Non async
Example 2 – Async
The answer I got the most was better performance, the idea that the second (async) example executes faster than the first example.
Although I wouldn’t say that this answer is completely incorrect, it is not the performance at the individual request level that improves. Instead it will be the general performance of your web application as a whole that will improve as the async version will give you beter scalability.
Why does the async method scales better?
Every time a request hits your server, a worker thread will process the request. A web server will typically have a limited number of worker threads available. Once the worker thread limit is reached, new requests will have to wait until a worker thread becomes available to process the request.
In the synchronous example above, the worker thread only becomes available after the request has completed. Although we have to wait for the database to return the list of products, the worker thread will just stop and wait.
If we compare this to the asynchronous example, the moment we do the database call, the await
keyword allows the current worker thread to detach from the program and go back to the thread pool. Once the database call is done, .NET will take another thread from the pool and continue the work. Meanwhile another request can be handled by the worker.
More information: https://learn.microsoft.com/en-us/aspnet/core/performance/performance-best-practices?view=aspnetcore-6.0#avoid-blocking-calls