开发者

WebRequest.BeingGetResponse and IAsyncResult.AsyncWaitHandle not working

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜