@Page Directives: Async
By default this is set to false. When should you set it to true? Why would you want a page to become asynchronous? In order to reduce the possibility of your thread-pool becoming jammed and unable to service requests. When a page has long-running I/O operations, such as a database call, the thread handling the request is waiting around doing nothing much in particular while the data is retrieved. When many threads are occupied like this you have a much greater chance of ending up with full pool, and sending the dreaded server unavailable message to your clients.
Asynchronous pages get around this by removing threads from the pool when the long-running operation starts, at which point a non-thread-pool-thread takes over. Then, when complete, a new thread-pool thread is added to the pool to finish servicing the request. No needlessly waiting threads, meaning a much more responsive thread-pool.
How do you tell the page to release the thread and how do you tell it to ask for another when ready? Well, when you set Async=”true” it tells ASP.NET to implement the page using the IHttpAsyncHandler. This allows you to call Page.AddOnPreRenderCompleteAsync so that you can register a Begin and End method, which should be done before Pre_Render ends. Once setup shortly after the Pre_Render event, the page calls the registered Begin method which returns an IAsyncResult. The page then uses this to get the call back that the asynchronous operation has completed, at which point the End method is fired. The operation in Begin should return an IAsyncResult – you can write your own if you need to or preferably use one of the .NET framework’s many implementations.
You can also use the MethodAsync method and MethodCompleted event in web service proxies, negating the need for registering the Begin and End methods above. Instead you register with the Completed event handler of the proxy.
What if you want to make multiple asynchronous calls? Or specify a timeout after which the asynchronous operation should abort? This is where asynchronous tasks come in which are, conveniently, the subject of the next and related @Page directive: AsyncTimeout.
In conclusion, the Async directive coupled with performing asynchronous operations post Pre_Render is essential if you want to be kind to your thread-pool threads by not letting them sit around getting soaked. This leads to ASP.NET applications that do not collapse due to a bursting thread pool that has all its threads out to lunch waiting for long running I/O operations. Which can only be a good thing.
References: