简体   繁体   中英

How do I make a .NET 4 thread wait for asynchronous requests to finish?

I am using HttpWebRequest.BeginGetRequest() to make 500 asynchronous HTTP requests from a single method. I would like that method to wait until I get a response from all the requests or they timeout.

What is the best way to do this?

I'm currently wrapping the asynchronous calls within a List of Task objects to use Tasks.WaitAll(), but I don't want to go too far down the rabbit hole before I know that this is a good solution.

Any ideas?

EDIT

I implemented counters, and they work, but I'm curious about using delegates like shown on this page.

Multi-threading and Async Examples

Has anybody done something like this before? Is it overkill?

I'm currently wrapping the asynchronous calls within a List of Task objects to use Tasks.WaitAll()

This is a fairly clean solution if you truly want to force these "tasks" to synchronize and block at this point. This is the main rationale behind Task.WaitAll() , and is nice since it (optionally) allows you to cancel the blocking operation after a timeout, if you so choose.

Personally I wouldn't block the thread, it defeats the purpose of the async model.

If I absolutely had to wait for these web requests to finish before continuing I would instead keep a counter that is incremented each time you get called back on a successful or failed request.

Check the counter on each callback and if it has hit your desired count then let the thread continue...

This way you can also keep your UI nice and responsive and perhaps update a counter/progress bar - Even if you're not kicking these off on the UI thread it's nice to provide some visual feed back tot he user about what is going on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM