Async=true Page and WebRequest problem

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm trying to use an Async="true" page to do an async HttpWebRequest. My
code is based on the MSDN example:

http://msdn2.microsoft.com/en-us/library/21k58ta7.aspx

The problem I'm having is that I'm not sure how to wait until my response
has finished arriving. It's jumping to EndGetAsyncData when I first get the
response instead of when I finish reading it. Looking at the code I can see
why it's doing this, but I'm not sure how I can fix it. I'm basically doing:

IAsyncResult BeginGetAsyncData(Object src, EventArgs args, AsyncCallback cb,
Object state)
{
IAsyncResult reslt = (IAsyncResult)Request.BeginGetResponse(cb,
WebRequestState);
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle,
new WaitOrTimerCallback(TimeoutCallback), Request, ConnectionTimeout * 1000,
true);

// The response came in the allowed time. The work processing
will happen in the
// callback function.
allDone.WaitOne();

// Release the HttpWebResponse resource if it ever got created
if (state.Response != null)
state.Response.Close();
}

void EndGetAsyncData(IAsyncResult ar)
{
RespCallback(ar);
}

Thanks for any insight!
 
Thus wrote demi,
I'm trying to use an Async="true" page to do an async HttpWebRequest.
My code is based on the MSDN example:

http://msdn2.microsoft.com/en-us/library/21k58ta7.aspx

The problem I'm having is that I'm not sure how to wait until my
response has finished arriving. It's jumping to EndGetAsyncData when
I first get the response instead of when I finish reading it. Looking
at the code I can see why it's doing this, but I'm not sure how I can
fix it. I'm basically doing:

IAsyncResult BeginGetAsyncData(Object src, EventArgs args,
AsyncCallback cb,
Object state)
{
IAsyncResult reslt = (IAsyncResult)Request.BeginGetResponse(cb,
WebRequestState);

ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle,
new WaitOrTimerCallback(TimeoutCallback), Request, ConnectionTimeout *
1000,
true);

// The response came in the allowed time. The work
processing
will happen in the
// callback function.
allDone.WaitOne();
// Release the HttpWebResponse resource if it ever got
created
if (state.Response != null)
state.Response.Close();
}
void EndGetAsyncData(IAsyncResult ar)
{
RespCallback(ar);
}
Thanks for any insight!

This seems to be one of the most popular pitfalls.

You cannot wait on the *callback's* completion using the AsyncWaitHandle.
Once the callback is called, the asynchronous operation
is completed -- that's why IsComplete will be true as well.

In order to wait for your callback's completion, use your own EventWaitHandle,
and Set() it at the end of your callback.

Cheers,
 
Back
Top