Title: Event Name Here
1(No Transcript)
2Asynchronous ASP.NET Programming
- Jeff Prosise
- Cofounder, Wintellect
- www.wintellect.com
3ASP.NET Threading
Worker process (aspnet_wp.exe or w3wp.exe)
IOCP Queue
I/O Threads
AppDomain 1
AppDomain 2
Worker Threads
Request Queue
AppDomain 3
4Thread Pool Saturation
External Devices
Database
Worker Threads
AppDomain
Web Service
Other
Thread pool depleted
Worker threads waiting for I/O operations to
complete
Requests
5Asynchronous Pages
- Begin processing on one thread and finish on
another - Ideal for ASP.NET Web pages that perform lengthy
external I/O operations - Remote database queries
- Remote Web service calls
- Include Async"true" in _at_ Page directive
- Optionally include AsyncTimeout, too
- Greatly simplified in ASP.NET 2.0
6How Async Pages Work
Normal page lifecycle
Async page lifecycle
PreInit
PreInit
Init
Init
InitComplete
InitComplete
PreLoad
PreLoad
Thread 1
Load
Load
Thread
LoadComplete
LoadComplete
PreRender
PreRender
PreRenderComplete
Begin
Async I/O
SaveState
End
SaveStateComplete
PreRenderComplete
Thread 2
Render
SaveState
SaveStateComplete
Render
7AddOnPreRenderCompleteAsync
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
8RegisterAsyncTask
void Page_Load(object sender, EventArgs e)
PageAsyncTask task new PageAsyncTask (
new BeginEventHandler (BeginAsyncOperation),
new EndEventHandler (EndAsyncOperation),
new EndEventHandler (TimeoutAsyncOperation),
null ) RegisterAsyncTask(task) IAsync
Result 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(IAsy
ncResult ar) // Called if async operation
times out (_at_ Page AsyncTimeout)
9How Do I Choose?
- AddOnPreRenderCompleteAsync
- Simple and easy to use
- Ideal for scenarios in which request performs
just one async I/O operation - RegisterAsyncTask
- Multiple I/O operations within one request
- Option of specifying time-out handler
- Flows context from thread 1 to thread 2
10Demo
11HTTP Handlers
- Classes that handle HTTP requests
- Implement the IHttpHandler interface
- ProcessRequest Handles requests
- IsReusable Determines poolability
- Standard handlers process requests for ASPX
files, ASMX files, and other file types - Custom HTTP handlers can be used to extend ASP.NET
12Simple HTTP Handler
using System.Web public class HelloHandler
IHttpHandler public void ProcessRequest
(HttpContext context) string name
context.Request"Name"
context.Response.Write ("Hello, " name)
public bool IsReusable get
return true
13ASHX Deployment
- Handlers can be deployed in ASHX files
- Eliminates the need to register the handler
- No changes to CONFIG files
- No changes to IIS metabase
- Eliminates the need to compile assembly
- ASHX handlers are autocompiled
14Hello.ashx
lt_at_ WebHandler Language"C" Class"HelloHandler"
gt using System.Web public class HelloHandler
IHttpHandler public void ProcessRequest
(HttpContext context) string name
context.Request"Name"
context.Response.Write ("Hello, " name)
public bool IsReusable get
return true
15Practical Uses for Handlers
- Custom HTTP handlers enjoy many uses
- Adding support for new file types
- Dynamic image generation
- Database image retrieval
- Using XSLT to convert XML into HTML
- Providing targets for XML-HTTP callbacks
- Increasing system scalability (async handlers)
- Few real-world applications do NOT benefit from
custom HTTP handlers!
16Asynchronous HTTP Handlers
- Implement IHttpAsyncHandler interface
- ProcessRequest - Never called
- IsReusable - Same as IHttpHandler.IsReusable
- BeginProcessRequest - Called to start request
- EndProcessRequest - Called after completion
- Increases scalability IF requests are I/O-bound
(as opposed to CPU-bound)
17Async 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
18Demo
19HTTP Modules
- Classes that hook into the HTTP pipeline
- Implement the IHttpModule interface
- Init Initializes the module
- Dispose Cleans up resources
- Standard HTTP modules provide key services to
ASP.NET (e.g., authentication, authorization,
sessions, and caching) - Custom HTTP modules can be used to extend ASP.NET
20Simple HTTP Module
using System using System.Web public class
BigBrotherModule IHttpModule public void
Init (HttpApplication application)
application.EndRequest new EventHandler
(OnEndRequest) void OnEndRequest
(Object sender, EventArgs e)
HttpApplication application (HttpApplication)
sender application.Context.Response.Write
("Bill Gates is watching you")
public void Dispose ()
21HttpApplication Events
Authenticate- Request
Resolve- RequestCache
PreRequest- HandlerExecute
BeginRequest
Authorize- Request
Acquire- RequestState
HTTP Handler
Request
HTTP Pipeline
Response
EndRequest
PostRequest- HandlerExecute
Update- RequestCache
Release- RequestState
22Asynchronous HTTP Modules
- HttpApplication fires events
- BeginRequest, AuthenticateRequest, etc.
- Events can be processed asynchronously
- Handlers must be registered explicitly using
HttpApplication.AddEventNameAsync methods
(AddOnBeginRequestAsync, AddOnAuthenticateRequestA
sync, etc.) - In Global.asax, override HttpApplication.Init
- Remember threading constraints!
23Async Event Handlers
public void Init (HttpApplication application)
AddOnPreRequestHandlerExecuteAsync (
new BeginEventHandler (BeginPreRequestHandlerExecu
te), new EndEventHandler
(EndPreRequestHandlerExecute)
) IAsyncResult BeginPreRequestHandlerExecute
(Object source, EventArgs e, AsyncCallback
cb, Object state) // TODO Begin async
operation and return IAsyncResult void
EndPreRequestHandlerExecute (IAsyncResult ar)
// TODO Get results of async operation
24Demo
25Rules for Clean Living
- Avoid Thread.Start
- Risks unconstrained thread growth
- Avoid ThreadPool.QueueUserWorkItem
- Steals threads from ASP.NET thread pool
- Avoid asynchronous delegates
- Steals threads from ASP.NET thread pool
- Use custom thread pools if necessary
26(No Transcript)