Using Asynchronous methods in .NET–Quick Notes
I developed these notes just as a way to keep myself sane while writing Async methods in C#.
Quick Recap – Two types of threads for an ASP.NET programmer
1. Regular Windows Systems thread
2. .NET App Pool threads – Same thread pool that ASP.NET itself uses to process requests. You would use a ThreadPool.QueueUserWorkItem to use such a thread for your server side task – and yes, you would be taking away some of ASP.NET’s resources that it needs to do request processing.
How many concurrent ASP.NET requests per CPU?
UP from 12 requests per CPU (in .NET 3.5 and below), there’s now 5,000 concurrent requests per CPU in ASP.NET 4 (and above).
Why use Async at all ?
Assume we have three operations – which take 100, 200 and 300 milliseconds respectively. With the synchronous call, total response time would be slightly more than 600 milliseconds. However, if the calls are made asynchronously, total response time would be slightly more than 300 milliseconds, because that is the duration of longest task/operation.
When to use Async ?
Anytime that your server side ASP.NET code is making a database call, or a web service call or a network call or talking to the file system, that can be done asynchronously.
While that operation is in progress ASP.NET doesn’t have to be consuming a thread which is a CPU resource on that box while that operation is taking place.
And then once the operation is finished, ASP.NET will do the work to bring that request (rehydrate it), and then let it proceed with the result.
When NOT to use Async? – IIS versus Database Bottlenecks
The IIS thread pool can often handle many more simultaneous blocking requests than a database server. If the database is the bottleneck, asynchronous calls will not speed up the database response. Without a throttling mechanism, efficiently dispatching more work to an overwhelmed database server by using asynchronous calls merely shifts more of the burden to the database. If your DB is the bottleneck, asynchronous calls won’t be the magic bullet.
MultiThreading versus Async
Multithreading could encompass many more scenarios than Async. Typically Async is a request-response model where the response is delayed.
Multithreading could mean – do more than one task – without any consideration to the results (for e.g. – a certain thread could be used for a fire and forget task).
What about Async and Await ?
Formalizes how non-blocking methods work in .NET.
Leave a Reply