从api'获取json的异步任务不是异步运行的

本文关键字:异步 任务 运行 json api 获取 | 更新日期: 2023-09-27 18:18:32

我是c#异步任务的新手。我想完成的是:- 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;
        }
    }

从api'获取json的异步任务不是异步运行的

[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
    }