Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread handling in ASP.NET Async Await operations

For long running operation, if the asp.net thread is freed up to server other requests. On which thread does the long running operation will get executed and how will it acquire asp.net thread upon its completion.

like image 540
Sunny Avatar asked Feb 07 '23 17:02

Sunny


1 Answers

As I describe on my blog, long-running I/O operations do not require a thread at all. Rather, they use naturally-asynchronous I/O, which does not require a thread.

Device drivers generally use DMA, and this allows the device to directly read/write out of the main system RAM. .NET complements this approach with an IOCP (I/O Completion Port) that is part of the thread pool, allowing a single thread (or very few threads) per appdomain to wait on huge numbers of I/O operations.

To answer the second half of your question, the asynchronous method will resume with the request context, but it might or might not be on the same thread it was on before the await. The more common scenario is when the I/O operation completes, it signals the IOCP, which takes a thread pool thread to do a bit of housekeeping (marking the Task as complete, etc), and then that same thread enters the ASP.NET request context and resumes executing the handler. This doesn't always happen - sometimes a thread switch is necessary - but it's the most common case.

like image 78
Stephen Cleary Avatar answered Feb 09 '23 06:02

Stephen Cleary