Parallel http requests

前端 未结 2 1016
悲哀的现实
悲哀的现实 2021-01-07 09:52

I have an app that making API requests to the last.fm website using the backgroundWorker. Initially I don\'t know how many request I\'m gonna need to make. The response cont

相关标签:
2条回答
  • 2021-01-07 09:56

    You can take advantage of HttpClient, assume you have list of urls:

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

    If you use async method, you can await all tasks finish like below:

    var results = await Task.WhenAll(tasks);
    
    0 讨论(0)
  • 2021-01-07 10:13

    You can do Async Web Request as well, using BeginGetResponse

          HttpWebRequest webRequest;
          webRequest.BeginGetResponse(new AsyncCallback(callbackfunc), null);
    
    
          void callbackfunc(IAsyncResult response)
          {
             webRequest.EndGetResponse(response);
          }
    
    0 讨论(0)
提交回复
热议问题