views:

15

answers:

1

WebRequest.BeginGetResponse returns IAsyncResult, which has a member AsyncWaitHandle. Initially, I thought that I could just wait on that in the initiating code. But it turns out that the event is signaled as soon as the request is made and before and not after EndGetResponse is called. This seems unintuitive for me but whatever.

So, I've looked for some examples out there and there seems to be two ways of going about it. One is simply to create a ManualResetEvent and pass that in as user state so that in the callback I can set it after EndGetResponse.

The other is to use ThreadPool.RegisterWaitForSingleObject. Something like:

ManualResetEvent waitHandle = new ManualResetEvent(false);

ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle,
    new WaitOrTimerCallback((s, t) => { waitHandle.Set(); }), null, -1, true);

waitHandle.WaitOne();

That works even if ugly. And looking at the MSDN documentation for BeginGetResponse, that's how the code sample does it.

My question is, passing in a ManualResetEvent as user state, seems to be much simpler to me. What benefit does this ThreadPool.RegisterWaitforSingleObject bring?

A: 

You use that WaitHandle to wait for that Request to get a Response. When the WaitHandle gets a signal you know that a Response has arrived, and then you call EndGetResponse to actually get the Response.

Onkelborg
Thanks - but the question is really about using ThreadPool.RegisterWaitForSingleObject vs. simple ManualResetEvent to wait for the async op to finish.
Jiho Han
I just reacted to this: But it turns out that the event is signaled as soon as the request is made and before and not after EndGetResponse is called. This seems unintuitive for me but whatever.
Onkelborg