Parallel http requests

前端 未结 2 1039
悲哀的现实
悲哀的现实 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);
    

提交回复
热议问题