HttpClient.GetAsync never returns on Xamarin.Android

I am working on an Android application, backed up by the main ASP.NET application hosted on Azure. I use a generic library project to test the basic material in the Console Application project before creating functions for the Xamarin.Forms project (Android only).
The following code fragment is run after in the web service, where Client is HttpClient :

 public static async Task<MyClass> GetInformationAsync(string accountId) { HttpResponseMessage response = await Client.GetAsync(UriData + "/" + accountId); response.EnsureSuccessStatusCode(); string responseContent = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<MyClass>(responseContent); } 

On the same computer / network, the code ends in less than a second in the console application, however, it never finishes (even waited a minute) in the Xamarin.Forms.Android project.
I find this strange, since the Android client can successfully log in to the web service using PostAsync .

However, there is a difference in how the Android client and the console client call GetInformationAsync .

While the client is Consoling it asynchronously:

  private static async void TestDataDownload() { ... var data = await WebApiClient.GetInformationAsync(myId); } 

Android client calls it synchronously

  public void MainPage() { ... var data = WebApiClient.GetInformationAsync(myId).Result; } 
+5
source share
1 answer

It seems like you have some kind of dead end. You might want to include code in which you are actually calling GetInformationAsync , as this is probably the source of the problem.

You can probably fix your problem:

  • Do not call GetInformationAsync in sync mode
  • Postfine your asynchronous calls to GetInformationAsync using ConfigureAwait(false) so that you don’t switch context with every method call.

So your GetInformationAsync method will look like this:

 public static async Task<MyClass> GetInformationAsync(string accountId) { var response = await Client.GetAsync(UriData + "/" + accountId).ConfigureAwait(false); response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return JsonConvert.DeserializeObject<MyClass>(responseContent); } 

Then, if you call it somewhere, you need to return it in the same context, Ie if you need to update the interface:

 var myClass = await GetInformationAsync(accountId); // update UI here... 

Otherwise, if you do not need to return in the same context:

 var myClass = await GetInformationAsync(accountId).ConfigureAwait(false); 
+10
source

All Articles