Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous Webrequest best practices

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?

like image 825
Andrew Harry Avatar asked Feb 23 '09 03:02

Andrew Harry


1 Answers

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.

like image 125
chuckj Avatar answered Sep 22 '22 05:09

chuckj