0
我是新的異步編程在asp中,我有一個問題和問題。我想連接到外部API和我創建類任務,這裏是類的一個znippetNET MVC,循環中的異步任務
public class Tasks
{
HttpClient httpc = new HttpClient();
public async System.Threading.Tasks.Task<String> getStations()
{
var uri = new Uri("http://api.gios.gov.pl/pjp-api/rest/station/findAll");
var response = await httpc.GetAsync(uri);
return await response.Content.ReadAsStringAsync();
}
public async System.Threading.Tasks.Task<String> getStationDetails(int id)
{
string path = "http://api.gios.gov.pl/pjp-api/rest/station/sensors/" + id;
var uri = new Uri(path);
var response = await httpc.GetAsync(uri);
return await response.Content.ReadAsStringAsync();
}
public async System.Threading.Tasks.Task<String> getStationValues(int id)
{
string path = "http://api.gios.gov.pl/pjp-api/rest/data/getData/" + id;
var uri = new Uri(path);
var response = await httpc.GetAsync(uri);
return await response.Content.ReadAsStringAsync();
}
然後我爲我的請求,其中,i準備數據以響應
public async Task<ActionResult> prepareAirContitionData(int id)
{
Task<string> taskStationDetails = tasks.getStationDetails(id);
string stationDetail = await taskStationDetails;
List<Station> stationsObj = JsonConvert.DeserializeObject<List<Station>>(stationDetail);
List<Task<string>> stationsValues = new List<Task<string>>();
foreach(var station in stationsObj)
{
stationsValues.Add(tasks.getStationValues(station.stationId));
}
string[] war = await Task.WhenAll(stationsValues.ToArray());
Console.Write(war);
return Json("", JsonRequestBehavior.AllowGet);
}
創建asyncronous控制器這是我的任務草案。問題出現在循環中,當我收集任務並等待它時,它們不顯示在我的字符串數組中,只填充一個變量。
,但我想準備數據REPONSE,我想處理這些數據 – PiotroSan
好,我想我幫我,我檢查這個解決方案 – PiotroSan
這不起作用我在所有循環中都有相同的值:/ – PiotroSan