raimone

raimone

  • NA
  • 2
  • 29.1k

Async Http Handler

Jan 9 2011 1:00 PM
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
    }
}