gpt4 book ai didi

c# - restsharp 发出多个异步请求

转载 作者:行者123 更新时间:2023-12-04 02:50:26 31 4
gpt4 key购买 nike

使用 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(它也可以反序列化数据 - 请参阅 http://restsharp.org/ )与任务可能如下所示:

// 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

关于c# - restsharp 发出多个异步请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55335673/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com