2015-10-20 273 views
0

我是新來的異步任務在c#中。我想做到的是以下幾點: - API調用3層其他的API異步 - 返回3個datatsets作爲一個異步任務從api的異步任務不運行異步

[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; 
     } 
    } 
+1

什麼是你的意思是它不是取它異步?因爲我向你保證它是。你的意思是? – Aron

+0

你是對的,我其實是同時說的。那裏的措辭不好。 :) – user1651985

回答

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 
    } 
+0

謝謝,等待Task.WhenAll工作。 :) – user1651985