Parallel HTTP Requests

I have an application that makes API requests to last.fm website using backgroundWorker. Initially, I do not know how many queries I will need to make. The answer contains the total number of pages, so I only get it after the first request. Here is the code below.

    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++;
        }

The problem is that the last.fm API is very slow, and it can take up to 5 seconds to respond. With a large number of pages, loading will take a long time.

I want to do parallel queries, say 3 parallel queries at a time. Is it possible? If so, how can I do this?

Many thanks.

+1
source share
2 answers

HttpClient, , URL-:

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

                //Do something more
            }));

async, , :

var results = await Task.WhenAll(tasks);
+7

Async Web Request, BeginGetResponse

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


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

Source: https://habr.com/ru/post/1686823/


All Articles