I'm currently developing a custom HttpHandler (for compressing/combining CSS, but that doesn't matter for this question).
I started with a simple reusable=true synchronous HttpHandler like we all know.
Now i'm trying to improve it to an asynchronous handler (as it uses IO functionality and it's used on a very busy website).
My first attempt (and this seems to work ok):
Action<HttpContext> asyncProcessRequest;
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
asyncProcessRequest = new Action<HttpContext>(ProcessRequest);
return asyncProcessRequest.BeginInvoke(context, cb, extraData);
}
public void EndProcessRequest(IAsyncResult result)
{
asyncProcessRequest.EndInvoke(result);
}
public virtual void ProcessRequest(HttpContext context)
{
// real work
}
This is a non-reusable httphandler (as from what I read, IsReusable should be false, because this handler has state (the asyncProcessRequest field).
Now I want to make this reusable. So my first thought was to create a dictionary of IAsyncResult / Action like this:
IDictionary<IAsyncResult, Action<HttpContext>> asyncProcessRequests;
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
if (asyncProcessRequests == null)
{
asyncProcessRequests = new Dictionary<IAsyncResult, Action<HttpContext>>();
}
var request = new Action<HttpContext>(ProcessRequest);
var result = request.BeginInvoke(context, cb, extraData);
asyncProcessRequests.Add(result, request);
return result;
}
public void EndProcessRequest(IAsyncResult result)
{
Action<HttpContext> action;
if (asyncProcessRequests.TryGetValue(result, out action))
{
action.EndInvoke(result);
}
}
Is this a correct pattern ? or am I way off?
It seems to work (I'm not getting any errors or weird behavior), but before putting this to production, I would like to verify with someone who has more experience than me in writing these Http handlers..
Thanks in advance!