Today I came across a brilliant explanation of c#'s await keyword. I've been trying to figure it out for a couple of weeks now and every time I read it the explanation gets too complicated too quickly. The essential problem is as follows:
Marking a method as Async doesn't make it Asynchronous
And therein lies the confusion.
(BTW I'm not sure which genius came up with this. Probably the same person who came up with "Visual Studio Online" - because.. you know.. it's not actually an online version of visual studio.)
So anyway marking a method as async doesn't make it asynchronous. What the heck does it do?
Async releases the thread from the server pool
Huh? Well, normally each request in IIS takes up a thread. While IIS has a bewildering number of performance tuning options it essentially has a fixed number of threads available to process simultaneous requests. Each request uses a thread. So normally, the maximum number of simultaneous requests possible comes down to the maximum number of threads. So, if suddenly 1000 users hit your app at the same time, the 1001st user's request is going to be put into a queue, and they will have to wait. Now if your queue size is say 5000, and you then suddenly get 5000 more users hitting the site, your 6001st user is going to get a 503 error.
Now if you're trying to squeeze more performance out of IIS, and your performance isn't being limited by the normal things (database, disk, memory), but by number of threads, you have a few options:
- Increase the maximum number of threads
- Increase the queue size
- Add more CPU's, which will probably give you more threads
- Use the await keyword
So if you're lucky enough to be able to call a method that is marked as async, during that call, an extra thread is going to be freed up. But only if the task is not CPU bound. Long running calculations? Forget it.
So what does this mean for us boring ASP.NET developers? Should we use await? In my opinion, nope. You are just needlessly engaging in good old premature optimisation. Just continue on as usual, nothing to see here.