02 Asynchronous ASP Net Programming by cPitDSc

VIEWS: 54 PAGES: 20

									Asynchronous ASP.NET
Programming
Agenda

• ASP.NET threading model
• Asynchronous pages
• Asynchronous HTTP handlers
• Other asynchronous models
ASP.NET Threading
  Worker process (aspnet_wp.exe or w3wp.exe)

    IOCP
    Queue     I/O Threads



                                         AppDomain #1




                                         AppDomain #2
   Request     Worker
    Queue      Threads



                                         AppDomain #3
Thread Pool Saturation
                                                      External Devices




            Worker                                       Database
            Threads            AppDomain




                                                           Web
                                                          Service




Requests   Thread pool   Worker threads waiting for
                                                           Other
           depleted      I/O operations to complete
Asynchronous Pages

• Begin processing on one thread and finish on
  another, consuming no threads in between
• Ideal for pages that perform lengthy I/O
  – Remote database queries
  – Remote Web service calls
• Page methods provide support
  – AddOnPreRenderCompleteAsync
  – RegisterAsyncTask
How Asynchronous Pages Work
 Normal page lifecycle   Async page lifecycle
          PreInit                 PreInit

            Init                    Init

        InitComplete            InitComplete

          PreLoad                 PreLoad

           Load                    Load

       LoadComplete            LoadComplete

         PreRender               PreRender

     PreRenderComplete             Begin
                                                 Async I/O
         SaveState                  End

     SaveStateComplete       PreRenderComplete

          Render                 SaveState

                             SaveStateComplete

                                  Render
AddOnPreRenderCompleteAsync
void Page_Load (object sender, EventArgs e)
{
    AddOnPreRenderCompleteAsync (
        new BeginEventHandler (BeginAsyncOperation),
        new EndEventHandler (EndAsyncOperation)
    );
}

IAsyncResult BeginAsyncOperation (object sender, EventArgs e,
    AsyncCallback cb, object state)
{
    // TODO: Begin async operation and return IAsyncResult
}

void EndAsyncOperation (IAsyncResult ar)
{
    // TODO: Get results of async operation
}
Multiple Asynchronous Operations

• Call AddOnPreRenderCompleteAsync
  multiple times (once per operation)
• Tasks are executed sequentially
  – In order of calls to
    AddOnPreRenderCompleteAsync
  – Next begin method not called until previous end
    method returns
• Concurrent execution requires you to
  compose IAsyncResult
AddOnPreRenderCompleteAsync
RegisterAsyncTask
void Page_Load(object sender, EventArgs e)
{
    PageAsyncTask task = new PageAsyncTask (
        new BeginEventHandler (BeginAsyncOperation),
        new EndEventHandler (EndAsyncOperation),
        new EndEventHandler (TimeoutAsyncOperation), null
    );
    RegisterAsyncTask(task);
}

IAsyncResult BeginAsyncOperation (object sender, EventArgs e,
    AsyncCallback cb, object state)
{
    // TODO: Begin async operation and return IAsyncResult
}

void EndAsyncOperation (IAsyncResult ar)
{
    // TODO: Get results of async operation
}

void TimeoutAsyncOperation(IAsyncResult ar)
{
    // Called if async operation times out (@ Page AsyncTimeout)
}
Multiple Asynchronous Tasks

• Call RegisterAsyncTask multiple times
  (once per task)
• Tasks can be executed sequentially or
  concurrently (in parallel)
  – Driven by fifth parameter to PageAsyncTask
    constructor
  – Parallelism constrained by thread availability
• No need to implement IAsyncResult!
Controlling Order of Execution
PageAsyncTask task1 =
    new PageAsyncTask (Begin1,
    End1, null, null, false);
RegisterAsyncTask(task1);
                                                  task1
PageAsyncTask task2 =
    new PageAsyncTask (Begin2,
    End2, null, null, true);
RegisterAsyncTask(task2);

PageAsyncTask task3 =                     task2           task3
    new PageAsyncTask (Begin3,
    End3, null, null, true);
RegisterAsyncTask(task3);



             false = Execute in series
             true = Execute in parallel
ExecuteRegisteredAsyncTasks

• Executes registered async tasks
  immediately
• Executes synchronously!
RegisterAsyncTask(task1);
RegisterAsyncTask(task2);
ExecuteRegisteredAsyncTasks(); // Execute task1 and task2 now
Context Flow

• RegisterAsyncTask flows request context
  from begin threads to end threads
  – HttpContext
  – Impersonation
  – Culture
• AddOnPreRenderCompleteAsync does not
  – HttpContext.Current == null in end threads
  – End threads revert to process identity
RegisterAsyncTask
Asynchronous HTTP Handlers

• Implement IHttpAsyncHandler interface
  – ProcessRequest - Never called
  – IsReusable - Same as IHttpHandler.IsReusable
  – BeginProcessRequest - Called to start request
  – EndProcessRequest - Called after completion
• Increases scalability of I/O-bound handlers
Asynchronous Handler Structure
public class AsyncHandler : IHttpAsyncHandler
{
    public void ProcessRequest (HttpContext context) {}
    public bool IsReusable { get { return true; } }

    public IAsyncResult BeginProcessRequest (HttpContext context,
        AsyncCallback cb, Object state)
    {
        // TODO: Begin async operation and return IAsyncResult
    }

    public void EndProcessRequest (IAsyncResult ar)
    {
        // TODO: Get results of async operation
    }
}
Asynchronous HTTP Handlers
Other Async Models

• Asynchronous HTTP modules
  – Handle pipeline events asynchronously
  – Register async event handlers with
    HttpApplication.AddOnEventNameAsync
    methods (e.g., AddOnBeginRequestAsync)
• Asynchronous ASMX Web services
  – Implement Web methods using familiar
    Begin/End pattern
  – Wsdl.exe does the rest
Discussion

								
To top