How to handle long requests with an HTTP handler in IIS?

I need to handle long requests inside IIS, processing the request itself is very easy, but it takes a lot of time mainly due to I / O. Basically I need to request another server, which sometimes requests a third server. Therefore, I want to process as many requests as I can at the same time. To do this, I need to process requests asynchronously, how to do it 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 above example, the thread is freed up as soon as I call the "Start ..." method and the response is sent to another thread, so you can easily achieve a very high concurrency value. How do you do the same in an HTTP handler inside IIS?

+6
source share
2 answers

You can implement HttpHandler with IHttpAsyncHandler . MSDN has a good walkthrough with examples on how to do this here .

+3
source

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 link multiple requests together, you can do it in async HttpHandler , but it is easier if you use async Page .

+3
source

Source: https://habr.com/ru/post/905020/


All Articles