ASP.NET 2.0 vastly simplifies the way you build asynchronous pages. Youbegin by including an Async="true" attribute in the page's @ Page directive, likeso:
<%@ Page Async="true" ... %>
Under the hood, this tells ASP.NET to implement IHttpAsyncHandler in thepage. Next, you call the new Page.AddOnPreRenderCompleteAsync methodearly in the page's lifetime (for example, in Page_Load) to register a Beginmethod and an End method, as shown in the following code:AddOnPreRenderCompleteAsync (new BeginEventHandler(MyBeginMethod),new EndEventHandler (MyEndMethod));What happens next is the interesting part. The page undergoes its normalprocessing lifecycle until shortly after the PreRender event fires. Then ASP.NETcalls the Begin method that you registered usingAddOnPreRenderCompleteAsync. The job of the Begin method is to launch anasynchronous operation such as a database query or Web service call and returnimmediately. At that point, the thread assigned to the request goes back to thethread pool. Furthermore, the Begin method returns an IAsyncResult that letsASP.NET determine when the asynchronous operation has completed, at whichpoint ASP.NET extracts a thread from the thread pool and calls your End method.After End returns, ASP.NET executes the remaining portion of the page'slifecycle, which includes the rendering phase. Between the time Begin returnsand End gets called, the request-processing thread is free to service other requests, and until End is called, rendering is delayed. And because version 2.0of the .NET Framework offers a variety of ways to perform asynchronousoperations, you frequently don't even have to implement IAsyncResult. Instead,the Framework implements it for you.The codebehind class in
provides an example. The correspondingpage contains a Label control whose ID is "Output". The page uses theSystem.Net.HttpWebRequest class to fetch the contents of http://msdn.microsoft.com. Then it parses the returned HTML and writes out tothe Label control a list of all the HREF targets it finds.
Figure 1 AsyncPage.aspx.cs