【问题标题】:Parallel http requests并行 http 请求
【发布时间】:2017-02-28 18:04:11
【问题描述】:

我有一个应用程序使用 backgroundWorker 向 last.fm 网站发出 API 请求。最初我不知道我需要提出多少请求。响应包含总页数,所以我只会在第一次请求后得到它。这是下面的代码。

    private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {            
        int page = 1;
        int totalpages = 1;

        while (page <= totalpages)
        {
            if (backgroundWorker.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            //Here is the request part
            string Response = RecentTracksRequest(username, from, page);

            if (Response.Contains("lfm status=\"ok"))
            {
                totalpages = Convert.ToInt32(Regex.Match(Response, @"totalPages=.(\d+)").Groups[1].Value);

                MatchCollection match = Regex.Matches(Response, "<track>((.|\n)*?)</track>");
                foreach (Match m in match)
                    ParseTrack(m.Groups[1].Value);
            }
            else
            {
                MessageBox.Show("Error sending the request.", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (page >= totalpages)
                break;

            if (totalpages == 0)
                break;

            if (page < totalpages)
                page++;
        }

问题是 last.fm API 真的很慢,可能需要 5 秒才能得到响应。页面多,加载时间长。

我想发出并行请求,例如一次 3 个并行请求。可能吗?如果是,我该怎么做?

非常感谢。

【问题讨论】:

  • 顺便说一句,如果您向同一主机(在您的情况下为 last.fm)发出请求,.NET 将限制并发 http 请求的数量。在此处查看接受的答案:stackoverflow.com/questions/1361771/…

标签: c# parallel-processing httpwebrequest


【解决方案1】:

您可以利用HttpClient,假设您有网址列表:

var client = new HttpClient();
var tasks = urls.Select(url => client.GetAsync(url).ContinueWith(t =>
            {
                var response = t.Result;
                response.EnsureSuccessStatusCode();

                //Do something more
            }));

如果您使用异步方法,您可以等待所有任务完成,如下所示:

var results = await Task.WhenAll(tasks);

【讨论】:

  • Parallel.ForEach的另一种方式
【解决方案2】:

您也可以使用 BeginGetResponse 进行异步 Web 请求

      HttpWebRequest webRequest;
      webRequest.BeginGetResponse(new AsyncCallback(callbackfunc), null);


      void callbackfunc(IAsyncResult response)
      {
         webRequest.EndGetResponse(response);
      }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 2014-08-06
    相关资源
    最近更新 更多