0
Answer

Async Http Handler

Ask a question
raimone

raimone

13y
9.7k
1
Looking for the correct way to run multiple api request from a single async http handler. The sample code below works for executing one process but I will like to run multiple at the same time (i.e. ar1.ProcessRequest, ar2.ProcessRequest, ect.). What would be the correct, and most efficient, way of achieving this?

Ex:

class AsyncHandler: IHttpAsyncHandler
{
   public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object state)
   {
APIAsyncResult _ar
_ar = new APIAsyncResult(cb, state);
_ar.ProcessRequest(_context); return _ar;
   }
    public void EndProcessRequest(IAsyncResult result)
    {
        _context.Response.ContentType = "text/plain";
    }
    public void ProcessRequest (HttpContext context) 
    {        
    }
    public bool IsReusable { get { return false; } }
}

//async class
class APIAsyncResult : IAsyncResult
{
    private AsyncCallback _cb;
    private object _state;
    private ManualResetEvent _event;
    private bool _completed = false;
    private object _lock = new object();

    public APIAsyncResult(AsyncCallback cb, object state)
    {
        _cb = cb;
        _state = state;
    }    
    public Object AsyncState { get { return _state; } }
    public bool CompletedSynchronously { get { return false; } }
    public bool IsCompleted { get { return _completed; } }

    public WaitHandle AsyncWaitHandle
    {
        get
        {
            lock (_lock)
            {
                if (_event == null)
                    _event = new ManualResetEvent(IsCompleted);
                return _event;
            }
        }
    }
    public void CompleteCall()
    {
        lock (_lock)
        {
            _completed = true;
            if (_event != null) _event.Set();
        }

        if (_cb != null) _cb(this);
    }
    public void ProcessRequest(HttpContext context)
    {
//api call stuff here
    }
}