restsharp发出多个异步请求

时间:2019-03-25 10:25:11

标签: c# restsharp

通过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);    

如您所见,城市请求要等到酒店请求响应后才能执行,但是我认为这两个请求都必须发送,并且要等到两个响应都回来后。

我该怎么做?

1 个答案:

答案 0 :(得分:4)

使用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