views:

1830

answers:

4

What is the best practice for getting a webrequest asynchronously?

I want to download a page from the internet (doesn't matter what) and avoid blocking a thread as much as possible.

Previously I believed that it was enough to just use the 'BeginGetResponse' and 'EndGetResponse' pair. But on closer inspection I also see that there is the option of using 'BeginGetRequestStream'

[UPDATE] GetRequestStream is used for POST operations

And then to add to the confusion, Should I be using stream.BeginRead and EndRead?

[UPDATE] this article suggests it is even better to process the HttpResponse.GetResponseStream asynchronously using Stream.BeginRead

What a mess!

Can someone point me in the right direction?

What is the Best Practice?

+1  A: 

The following article appears to have a good tutorial on using HttpWebRequest asynchronously using threads:

http://www.developerfusion.com/code/4654/asynchronous-httpwebrequest/

Ben Blank
A: 
  1. You use Begin/EndGetResponse to asynchonously wait for the HTTP response. If you are doing a POST and need to send a lot of data asynchronously, use Begin/EndGetRequestStream.

  2. This isn't unique to asynchronous communication - you can look up the synchronous versions to get additional info.

  3. I'm not sure why you would be doing a Read on the request stream - most likely you'll be writing to it, and reading from the Response stream.

Finally, Jeffrey Richter's blog has an article about some of the subtleties of HttpWebRequest and streams.

mbeckish
yes i think i was confused with the purpose of 'BeginGetRequestStream'
Harry
A: 

Have you considered doing the web request in a new thread?

http://msdn.microsoft.com/en-us/library/ms173178.aspx

jayrdub
starting a new thread is less than ideal. Simply Blocking another thread isn't helping this application to scale
Harry
+3  A: 

You could code this all yourself or you could just use WebClient which does a lot of the grunt work for you. For example, to download file as a string you would call DownloadStringAsync() which eventually will trigger the OnDowloadStringCompleted event. If the file is binary you might try using DownloadDataAsync() instead.

chuckj