arielorvits arielorvits - 2 months ago 15
ASP.NET (C#) Question

async await advantages when we have enough threads

I understood that .net know to use multiple threads for multiple requests.

So, if probably our service wont get more request than the number of threads our server can produce (it look like huge number), the only reason I can see to use async is on single request that do multiple blocking operations which can done in parallel.

Am I right?

Another advantage may be that serve multiple requests with same thread is cheaper than use multiple threads. How significant is this difference?

(note: no UI exists in our service (I saw that there is single thread for this, but it isn't relevant))

thanks!

Answer

Am I right?

No, doing multiple independent blocking operations, is the job of Concurrent APIs anyway (though sometimes they need Synchronization (like lock, mutex) to maintain the object state and avoid Race condition), but the usage of Async-Await is to schedule the IO Operations, like File Read / Write, call a remote service or Database Read / Write, which doesn't need a thread, as they are queued on a queue in hardware called IO Completion ports.

Benefits of Async-Await:

  1. Doesn't start a IO operation on a separate Thread, since Thread is a costly resource, in terms memory and resource allocation and would do little precious than wait for IO call to come back. Separate thread shall be used for the compute bound operations, no IO bound.
  2. Free up the UI / caller thread to make it completely responsive to carry out other tasks / operations
  3. This is the evolution of Asynchronous programming model (BeginXX, EndXX), which was fairly complex to understand and implement

Another advantage may be that serve multiple requests with same thread is cheaper than use multiple threads. How significant is this difference?

Its a good strategy depending on the kind of request from caller, if they are compute bound better invoke a Parallel API and finish them fast, IO bound there's Async-Await, only issue with multiple threads is Resource allocation and Context switching, which needs to be factored in, but on other end it efficiently utilize the processor cores, which are fairly under utilized in the current day systems, as you would see most of the time processor is lying idle