c# - HttpWebRequest.Begin GetRequestStream() 最佳实践

标签 c# http httpwebrequest

我正在开发一个从各种服务收集数据的异步 Http 爬虫,目前,我正在使用执行串行 HttpWebRequest 调用以从服务发布/获取数据的线程池。

我想过渡到异步 Web 调用(BeginGetRequestStream 和 BeginGetResponse),我需要一些方法来获取响应数据和 POST 统计信息(写入完成的百分比,完成时(完成时更重要)等)。我目前有一个从生成/包含线程的对象调用的事件,表明已收到 HTTP 数据。我可以附加到 WebRequests 中的事件来调用已经实现的事件吗?这将是最无缝的过渡。

感谢您的帮助!

最佳答案

我刚刚从 this article 复制/粘贴(并编辑)了以下代码关于异步 Web 请求。它展示了一种基本模式,即如何以某种有条理的方式编写异步代码,同时跟踪哪些响应与哪些请求等。当您完成响应时,只需触发一个事件通知 UI响应完毕。

private void ScanSites ()
{
  // for each URL in the collection...
  WebRequest request = HttpWebRequest.Create(uri);

  // RequestState is a custom class to pass info
  RequestState state = new RequestState(request, data);

  IAsyncResult result = request.BeginGetResponse(
    new AsyncCallback(UpdateItem),state);
}

private void UpdateItem (IAsyncResult result)
{
  // grab the custom state object
  RequestState state = (RequestState)result.AsyncState;
  WebRequest request = (WebRequest)state.request;
  // get the Response
  HttpWebResponse response =
    (HttpWebResponse )request.EndGetResponse(result);

  // fire the event that notifies the UI that data has been retrieved...
}

请注意,您可以将 RequestState 对象替换为您想要的任何类型的对象,以帮助您跟踪事物。

您可能已经这样做了,但如果没有,我相信这是解决问题的完全可接受且干净的方法。如果这不是您想要的,请告诉我。

关于c# - HttpWebRequest.Begin GetRequestStream() 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5098494/

相关文章:

c# - Selenium 2(网络驱动程序): Taking a Screenshot returns a black image

http - 在不同位置提供静态文件

asp.net-mvc - 如何从 HttpAuthenticationContext 获取自定义 header 值

c# - “System.Net.FileWebRequest”无法在远程机器上转换为 'System.Net.HttpWebRequest',但可以在本地运行

C# : How to get SSL handshake response before proceeding to HttpWebrequest?

c# - HttpWebRequest 非常慢!

c# - 不属于 Windows 组或事件目录的人将如何访问 TFS 项目?

c# - 居中空数据模板

c# - 找到包含特定子元素的父元素

Linux命令发送HTTP API