RestSharp如何进行多个异步请求?

6

使用restsharp.org请求API很容易, 但当我需要调用两个不同的API时,第一个请求会保持代码,等到响应后才开始第二个请求,我认为这不正确, 以下是我的代码:

var client = new RestClient("http://xxx.yyy.com/");

var requestHotels = new RestRequest("api/hotelUi/home/hotelList", Method.POST);
requestHotels.AddParameter("take", "16");                                               
IRestResponse hotels = client.Execute(requestHotels); 
List<Hotel> topHotels = JsonConvert.DeserializeObject<List<Hotel>>(hotels.Content); 

var requestCities = new RestRequest("api/hotelUi/home/cityList", Method.POST);
requestCities.AddParameter("take", "16");                                                 
IRestResponse cities = client.Execute(requestCities);
List<City> topCities = JsonConvert.DeserializeObject<List<City>>(cities.Content);    

你看到的是城市请求等待酒店请求响应,但我认为它们两个都必须发送,并等待两个响应都返回。

我该怎么做呢?


你可以使用ExecuteAsync或ExecuteTaskAsync方法来代替Execute。 - Wokuo
@Wokuo 怎么办?在示例中没有多个请求,我如何理解这两个请求都已完成? - mohammad adibi
1
这篇文章并不是专门为RestSharp而写的,但你可以将它应用到RestSharp中。为了使用建议的ExecuteAsync方法,你必须理解async/await。 - Crowcoder
1个回答

6
评论是正确的,使用ExecuteAsync(它也可以反序列化数据-请参阅http://restsharp.org/)与Tasks一起使用可能如下所示:
// Set up requests as before
var client = new RestClient("http://xxx.yyy.com/");

var requestHotels = new RestRequest("api/hotelUi/home/hotelList", Method.POST);
requestHotels.AddParameter("take", "16");  

var requestCities = new RestRequest("api/hotelUi/home/cityList", Method.POST);
requestCities.AddParameter("take", "16");     

var cancellationTokenSource = new CancellationTokenSource();

var hotelsTask = client.ExecuteTaskAsync<List<Hotel>>(requestHotels, cancellationTokenSource.Token);
var citiesTask = client.ExecuteTaskAsync<List<City>>(requestCities, cancellationTokenSource.Token);

var tasks = new List<Task> { hotelsTask, citiesTask };

// Pause execution here until both tasks are complete
await Task.WhenAll(tasks);

// Check status then use hotelsTask.Result and citiesTask.Result

集合初始化程序的最佳重载Add方法'List<Task>.Add(Task)'具有一些无效参数。 - mohammad adibi
client.ExecuteTaskAsync(requestHotels, cancellationTokenSource.Token),请为其他人完成您的答案,谢谢,https://dev59.com/umEi5IYBdhLWcg3wBH2J#21779724 - mohammad adibi
我已经改变了示例,使用ExecuteAsyncTask方法。我没有数据来测试响应,但是您应该能够检查这两个任务对象并找到您需要的内容。 - Greg Stanley

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接