I'm having trouble getting this to work correctly. It seems that if I shoot off multiple asynchronous calls in the begin function, no matter what I do, I only get one of them in the end function. How can I set this up to do more than one call?
If I use the same callback for all function, they all complete (I can write to a file and all responses are there), but only one has access to the HttpContext, I need them all too write to HttpContext.Response.
I've tried using WaitHandler.WaitAll, I only seem to ever get one response (even if I hold on to all the IAsyncResults).
I think I have to extend the IAsyncResult class to handle many results at once. If anyone can point me in the right direction I'd be much obliged.
Here are some snippets of my code:
public void Init(HttpApplication oApplication)
{
oApplication.AddOnPreRequestHandlerExecuteAsync(new BeginEventHandler(BeginPreRequestHandlerExecute), new EndEventHandler(EndPreRequestHandlerExecute));
}
public IAsyncResult BeginPreRequestHandlerExecute(Object oSource, EventArgs eArgs, AsyncCallback fCallBack, Object oState)
{
HttpWebRequest oReq = null;
IAsyncResult oResult = null;
string sPostStream = "<some_xml/>";
Uri oUri = new Uri("http://yahoo.com");
oReq = (HttpWebRequest)WebRequest.Create(oUri);
oReq.ContentType = "text/xml";
oReq.Method = "POST";
AsyncState oReqState = new AsyncState(oReq,fCallBack,Encoding.UTF8.GetBytes(sPostStream));
oResult = oReq.BeginGetRequestStream(new AsyncCallback(EndRequestStream), oReqState);
return oResult;
}
public void EndPreRequestHandlerExecute(IAsyncResult oResultMain)
{
XmlDocument oXml = new XmlDocument();
AsyncState oState = (AsyncState)oResult.AsyncState;
HttpWebRequest oReq = oState.oReq;
using (HttpWebResponse oResp = (HttpWebResponse)oReq.EndGetResponse(oResult))
{
using (Stream oResponse = oResp.GetResponseStream())
{
oXml.Load(oResponse);
oResponse.Close();
}
oResp.Close();
}
}