繁体   English   中英

C#-如何在后台发出Http Request并在完成后显示结果?

[英]C# - How to make an Http Request in the background and show the result once it's done?

我正在使用Xamarin构建一个Android应用,该应用可从Riot Games API中获取数据并显示给用户。 我希望在后台发出HTTP请求并更新UI。 我尝试使用ThreadPool.QueueUserWorkItem(),但是它立即执行下面的代码,我希望它等待直到抓取数据。 这是我的可移植类库中的代码。

 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();
}

谢谢!

更改:

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

带有:

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

并在'delegate'之前添加'async'关键字;

您正在使用异步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();
};

有关asyncawait更多信息, 请参阅我的博客

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM