This is another post in a series of posts on creating performant and scalable web APIs using ASP.NET Core. In this post, we’ll focus on making our code asynchronous, and hopefully making our API work more efficiently …
Up to now, in this blog series, all our API code has been synchronous - i.e. we haven’t used async / await yet. For synchronous API code, when a request is made to the API, a thread from the thread pool will handle the request. If the code makes an I/O call (like a database call) synchronously, the thread will block until the I/O call has finished. The blocked thread can’t be used for any other work, it simply does nothing and waits for the I/O task to finish. If other requests are made to our API whilst the other thread is blocked, different threads in the thread pool will be used for the other requests.
There is some overhead in using a thread - a thread consumes memory and it takes time to spin a new thread up. So, really we want our API to use as few threads as possible.
If the API was to work in an asynchronous manner, when a request is made to our API, a thread from the thread pool handles the request (as in the synchronous case). If the code makes an asynchronous I/O call, the thread will be returned to the thread pool at the start of the I/O call and then be used for other requests.
So, making operations asynchronous will allow our API to work more efficiently with the ASP.NET Core thread pool. So, in theory, this should allow our API to scale better - let’s see if we can prove that
#asp.net #.net core #api