2016-12-14 64 views
0

我正在用Xamarin構建一個Android應用程序,用於從Riot Games API抓取數據並顯示給用戶。我希望HTTP請求在後臺進行,並在完成後更新我的UI。我嘗試使用ThreadPool.QueueUserWorkItem(),但它立即執行下面的代碼,我希望它等到抓取數據。這是我的便攜式類庫上的代碼。C# - 如何在後臺創建Http請求並在完成後顯示結果?

public void GetSummonerInformation() 
     { 
      try 
      { 
        HttpResponseMessage response = httpClient.GetAsync(url).Result; 
        response.EnsureSuccessStatusCode(); 
        string result = response.Content.ReadAsStringAsync().Result; 

        var data = JsonConvert.DeserializeObject<Dictionary<string, App2.Models.SummonerDto>>(result); 

        var name1 = data.First().Value.name; 
        var id = data.First().Value.id; 
        var profileIconId1 = data.First().Value.profileIconId; 
        var revisionDate1 = data.First().Value.revisionDate; 
        sumId = id; 
        sumName1 = name1; 
        sumProfileIconId = profileIconId1; 
        sumRevisionDate = revisionDate1; 
        System.Diagnostics.Debug.WriteLine("{0} this is the {1}", data.First().Value.name, data.First().Value.profileIconId); 

      }catch(Exception ex) 
      { System.Diagnostics.Debug.WriteLine(ex.Message); } 

,這是我的代碼在我的Android mainactivity.cs

button2nd.Click += delegate 
      { 
        //Runs the http request on a background thread so the application doesnt hang.Need to make the code after that to wait for the request to end and then exexute 
        //because it gives me a blank icon and i need to press the button again. 
       ThreadPool.QueueUserWorkItem(o => mclass.GetSummonerInformation()); 
       System.Diagnostics.Debug.WriteLine(MyClass.sumProfileIconId); 
       iconUrl = string.Format("http://ddragon.leagueoflegends.com/cdn/6.24.1/img/profileicon/" + MyClass.sumProfileIconId + ".png"); 
       DisplaySummonerIcon(); 
       DisplaySummonerInformation(); 
} 

謝謝!

+0

使用BackgroundWorker ... – Mohit

回答

0

變化:

ThreadPool.QueueUserWorkItem(o => mclass.GetSummonerInformation()); 

有了:

await Task.Run(() => mclass.GetSummonerInformation()); 

並添加之前 '代理' '異步' 的關鍵字;

+0

它是否比上述用戶的背景工作者有優勢? –

0

您使用異步的API(HttpClient),所以你應該使用await

public async Task GetSummonerInformationAsync() 
{ 
    try 
    { 
    HttpResponseMessage response = await httpClient.GetAsync(url); 
    response.EnsureSuccessStatusCode(); 
    string result = await response.Content.ReadAsStringAsync(); 
    var data = JsonConvert.DeserializeObject<Dictionary<string, App2.Models.SummonerDto>>(result); 
    ... 
    System.Diagnostics.Debug.WriteLine("{0} this is the {1}", data.First().Value.name, data.First().Value.profileIconId); 
    } 
    catch(Exception ex) 
    { 
    System.Diagnostics.Debug.WriteLine(ex.Message); 
    } 
} 

援引爲這樣:

button2nd.Click += async (_, __) => 
{ 
    await mclass.GetSummonerInformationAsync(); 
    System.Diagnostics.Debug.WriteLine(MyClass.sumProfileIconId); 
    iconUrl = string.Format("http://ddragon.leagueoflegends.com/cdn/6.24.1/img/profileicon/" + MyClass.sumProfileIconId + ".png"); 
    DisplaySummonerIcon(); 
    DisplaySummonerInformation(); 
}; 

更多有關asyncawaitsee my blog

+0

謝謝你的回答!我最後使用了一個後臺工作者來實現它。使用你的方式有沒有好處? –

+0

@AlexTselikas:是的。 1)代碼使用'await'而不是'Completed'事件更清晰。 2)'await'不會浪費等待HTTP下載的線程。 –

+0

但使用await,我的應用程序跳過框架。 –

相關問題