HttpClient.GetAsync never returns on Xamarin.Android

前端 未结 1 1937
礼貌的吻别
礼貌的吻别 2020-12-18 07:42

I am working on an Android application, backed up by an ASP.NET Core application hosted on Azure. I am using a shared Library project to test basic stuff on a Console Applic

相关标签:
1条回答
  • 2020-12-18 07:59

    It seems like you are experiencing a deadlock of some sort. You might want to include the code where you actually call GetInformationAsync, as it is probably where the problem source is.

    You can probably fix your issue by:

    1. Not calling GetInformationAsync in a sync way
    2. Postfixing your async calls in GetInformationAsync with ConfigureAwait(false) to not switch context on every method call.

    So your GetInformationAsync method would look 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 back on the same context, I.e. if you need to update UI:

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

    Otherwise if you don't need to return on the same context:

    var myClass = await GetInformationAsync(accountId).ConfigureAwait(false);
    
    0 讨论(0)
提交回复
热议问题