[英]How to process long running requests with an HTTP handler under IIS?
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. 我需要在IIS中处理长时间运行的请求,处理请求本身非常轻量级,但主要是由于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 : 使用Socket类我可以轻松地写出类似的东西:
// ..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 . 在上面的例子中,一旦我调用“Begin ...”方法就释放线程,并且响应在另一个线程上发送,因此您可以轻松实现非常高的并发性。 How do you do the same in an HTTP handler inside IIS? 你如何在IIS内的HTTP处理程序中做同样的事情?
You can implement an HttpHandler with IHttpAsyncHandler
. 你可以实现与一个HttpHandler IHttpAsyncHandler
。 MSDN has a nice walkthrough with examples on how to do that here . MSDN有一个很好的演练,其中有关于如何在此处执行此操作的示例。
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
. 如果需要将多个请求链接在一起,则可以在异步HttpHandler
,但如果使用异步Page
HttpHandler
容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.