我是c#中async Task的新手。我想要完成的是: - Api调用3个其他api的异步 - 将3个数据集作为一个
返回[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Mvc.HttpGet]
public async Task<string> ServiceModelsForTournamentBase(int id)
{
var matchInfoJson = await GetJsonFromApi("api/asyncdata/searchmatchfortournament/" + id, _siteUrl);
var scoringPlayersJson = await GetJsonFromApi("api/asyncdata/scoringplayersfortournament/" + id, _siteUrl);
var teamsJson = await GetJsonFromApi("api/asyncdata/tournamentteams/" + id, _siteUrl);
// return json containing all three
}
private async Task<string> GetJsonFromApi(string serviceUrl, Uri siteUrl)
{
using (var client = new HttpClient())
{
client.BaseAddress = siteUrl;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync(serviceUrl);
return response.IsSuccessStatusCode
? await response.Content.ReadAsStringAsync()
: string.Empty;
}
}
答案 0 :(得分:1)
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Mvc.HttpGet]
public async Task<string> ServiceModelsForTournamentBase(int id)
{
var jsons = await Task.WhenAll(
GetJsonFromApi("api/asyncdata/searchmatchfortournament/" + id, _siteUrl),
GetJsonFromApi("api/asyncdata/scoringplayersfortournament/" + id, _siteUrl),
GetJsonFromApi("api/asyncdata/tournamentteams/" + id, _siteUrl)
);
var matchInfoJson = jsons[0];
var scoringPlayersJson = jsons[1];
var teamsJson = jsons[2];
// return json containing all three
}