C# – httpclient.getasync will never return on xamarin.android

I am developing an Android application supported by the asp.net core application hosted on azure. Before using the functions of xamarin.forms (Android only) project, I am using the shared library project to test the basic contents of the console application project. After logging in to the web service, run the following code, where the 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 is completed on the console application in less than a second. However, it will never be completed in the xamarin.forms.android project (even wait a minute). I find this strange because the Android client can successfully log in to the web service using postasync

However, how Android client and console client call getinformationasync is different

The console client calls it asynchronously:

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

Android clients call it synchronously

 public void MainPage()
 {
      ...
      var data = WebApiClient.GetInformationAsync(myId).Result;
 }

resolvent:

It seems that you have encountered some kind of deadlock. You may want to include the code where you actually call getinformationasync, because it may be the source of the problem

You can solve the problem in the following ways:

>Do not call getinformationasync synchronously > use configureawait (false) to suffix asynchronous calls in getinformationasync to not switch context on each method call

So your getinformationasync method looks like:

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 it to return the same context, that is, if you need to update the UI:

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

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

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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>