2017-10-17 17 views
0

我发现我的Xamarin Android应用程序运行速度很慢,因此我添加了一些异步/等待代码来提高性能。我想从UI线程中排除我的API调用。我认为这将是使用异步/等待的绝好机会。所以,我在函数的签名中添加了异步,并在我的返回值类型周围包装了Task。然后我用“await client.ExecuteTaskAsync”更新了RestSharp GET调用。一旦我这样做,我发现我需要更新我的调用GetCustInfo函数。我只需要添加.Result到通话结束,它没有显示任何错误。问题是它挂在GetCustInfo的调用上,并且不起作用。Xamarin Android应用程序 - 向API调用添加异步/等待以提高性能的问题

我在这里做错了什么?

public async Task<List<CustInfo>> GetCustInfo(string strBranchNumber, string dblCurrentXCoordinate, string dblCurrentYCoordinate) 
    { 
     if (this.strBearerToken == string.Empty) 
     { 
      throw new ArgumentException("No Bearer Token Found"); 
     } 

     try 
     { 
      var restUrl = this.strCustomerInfoAPIURL; 
      var uri = new Uri(string.Format(restUrl, string.Empty)); 

      var client = new RestClient(uri); 
      var request = new RestRequest(Method.GET); 
      request.AddHeader("Authorization", "bearer " + this.strBearerToken); 
      request.AddParameter("intBranchNumber", strBranchNumber); 
      request.AddParameter("intZipCode", this.strZipCode); 
      request.AddParameter("intCustomerType", this.strCustomerType); 
      request.AddParameter("intMinTotalAmount", this.strMinRevenue); 
      request.AddParameter("dblCurrentXCoordinate", dblCurrentXCoordinate); 
      request.AddParameter("dblCurrentYCoordinate", dblCurrentYCoordinate); 
      request.AddParameter("bolGetLocation", true); 

      var response = await client.ExecuteTaskAsync(request);     
      return JsonConvert.DeserializeObject<List<CustInfo>>(response.Content).OrderBy(x => x.ApproxDistance).ToList(); 
     } 
     catch (Exception ex) 
     { 
      return null; 
     } 
    } 

所以发生的是,当我打电话从异步/ AWAIT功能我的OnCreate当我尝试调用customer.GetCustomerInfo它只是停止()。

protected override void OnCreate(Bundle bundle) 
    { 
     .... 

      this.tableItems = customer.GetCustInfo(
       "xxxxxxx", 
       this.currentLocation.Latitude.ToString(), 
       this.currentLocation.Longitude.ToString()).Result; 
      this.listView.Adapter = new ListOfLocationAdapter(this, this.tableItems); 

    } 
+1

OnCreate本身位于您输入的操作的UI线程中,而不是异步,并且您没有等待对GetCustInfo的调用。所以它表现得像一个阻塞呼叫。在UI生命周期中使用不同的事件来触发它,并使用'await'语法来调用它。 – dlatikay

+0

你能举一个你的意思吗? UI生命周期中的所有事件都不会成为UI线程的一部分吗? –

+0

我做了一些研究,发现我应该在生命周期内的OnStart调用中将我的调用添加到custinfo中。这是工作。谢谢你的提示! –

回答

0

更改呼叫

this.tableItems = await customer.GetCustInfo(.. 

,并让我们知道.. 在您使用的结果从没有期待已久的电话,这显然会挂起的下一行,无论崩溃:

this.listView.Adapter = new ListOfLocationAdapter(this, **this.tableItems**); //this.tableItems is just empty 
+0

只需创建一个包含OnCreate完整内容的异步函数,并且无需等待就可以调用它,现在可以加快速度并实现您想要的效果。 –