Reputation: 8099
I need to process long running requests inside IIS, handling the request itself is very lightweight but takes a lot of time mostly due to IO. Basically I need to query another server, which sometimes queries a third server. So I want to process as many requests as I can simultaneously. For that I need to process the requests asynchronously how do I do that correctly?
Using the Socket class I could easily write something like :
// ..listening code
// ..Accepting code
void CalledOnRecive(Request request)
{
//process the request a little
Context context = new Context()
context.Socket = request.Socket;
remoteServer.Begin_LongRunningDemonicMethod(request.someParameter, DoneCallBack, context);
}
void DoneCallBack( )
{
IAsyncresult result = remoteServer.Begin_CallSomeVeryLongRunningDemonicMethod( request.someParameter, DoneCallBack, context);
Socket socket = result.Context.Socket;
socket.Send(result.Result);
}
In the example above the thread is released as soon as I call the "Begin..." method, and the response is sent on another thread, so you can easily achieve very high concurrency . How do you do the same in an HTTP handler inside IIS?
Upvotes: 6
Views: 1699
Reputation: 18652
Start with something like this:
public class Handler : IHttpAsyncHandler {
public void ProcessRequest(HttpContext context)
{
}
public IAsyncResult BeginProcessRequest(HttpContext context,
AsyncCallback cb, object extraData)
{
IAsyncResult ar = BeginYourLongAsyncProcessHere(cb);
return ar;
}
public void EndProcessRequest(IAsyncResult ar)
{
Object result = EndYourLongAsyncProcessHere(ar);
}
public bool IsReusable { get { return false; } }
}
If you need to chain multiple requests together, you can do so in an async HttpHandler
, but it's easier if you use an async Page
.
Upvotes: 3
Reputation: 141703
You can implement an HttpHandler with IHttpAsyncHandler
. MSDN has a nice walkthrough with examples on how to do that here.
Upvotes: 3