8

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?

4

3 回答 3

5

您可以自己编写代码,也可以只使用 WebClient 来为您完成大量繁重的工作。例如,要将文件下载为字符串,您将调用 DownloadStringAsync() 最终将触发 OnDowloadStringCompleted 事件。如果文件是二进制文件,您可以尝试使用 DownloadDataAsync() 代替。

于 2009-02-24T08:22:06.557 回答
0

您是否考虑过在新线程中执行 Web 请求?

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

于 2009-02-24T07:06:13.383 回答
0
  1. 您使用 Begin/EndGetResponse 异步等待 HTTP 响应。如果您正在执行 POST 并且需要异步发送大量数据,请使用 Begin/EndGetRequestStream。

  2. 这不是异步通信所独有的——您可以查找同步版本以获取更多信息。

  3. 我不确定您为什么要对请求流进行读取 - 很可能您将写入它,并从响应流中读取。

最后,Jeffrey Richter 的博客有一篇关于 HttpWebRequest 和流的一些微妙之处的文章。

于 2009-02-23T04:17:21.380 回答