Xamarin.Android HTTP Random Times

advertisements

I have a method that executes several HTTP requests called LoadServers() A button that executes LoadServers(). For my issue I only tap the button once the previous LoadServers() call has finished. A progress dialog appears while loading so I can only execute them serially.

Once in about every 10-15 calls to LoadServers results in the first http request to delay for almost exactly 10 seconds. The average time for LoadServers to complete is less than a half second and never more than 1 second. This only happens on Xamarin.Android. The delay does not happen on Xamarin.iOS and all of this code is shared.

Here is my code

private async Task LoadServers() {
    await Get();
    await Post();
    await Get();
    await Get();
    await Post();
}

private async Task Get() {
    var url = _httpClient.BaseAddress + model.GetToken();
    Log("Attempting to send GET to: " + url);
    using (var response = await _httpClient.GetAsync(url))
    {
        var resultContent = await response.Content.ReadAsStringAsync();
        Log("Got response back from : " + url + ": " + resultContent);
    }
}

private async Task Post() {
    var content = requestData.GetToken() + "=" + requestData.PostBody ();
    var request = new StringContent(content)
    {
        Headers = { ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded") }
    };
    var url = _httpClient.BaseAddress + "/No_content";
    Log ("Attempting to send POST to: " + url + "  with content: " + content);
    using (var response = await _httpClient.PostAsync(url, request))
    {
        string resultContent = await response.Content.ReadAsStringAsync();
        Log("Got response back from : " + url + ": " + resultContent);
    }
}

Every 15 or so executions of LoadServers() results in the following log statements:

Thread started:  #37
Thread finished:  #37
[2017-01-21T13:42:30.8841620-06:00] [debug] Loading Servers
[2017-01-21T13:42:30.8946770-06:00] [debug] Attempting to send GET to: XXX
Thread finished: <Thread Pool> #23
Thread started: <Thread Pool> #38
[2017-01-21T13:42:40.9550360-06:00] [debug] Got response back from : XXX <-- Notice the time (~10 seconds)

Does this have to do with resource consumption for the HTTP request? It attempts to clean up the resources and pauses execution until that happens? I'm not sure exactly what happens when it execute the request. Does it start a new thread?


Figuring out the exact issue is tough, and I'm unable to reproduce it. However, the wrapping of System.Net and the default MessageHandler in the HttpClient is not completely optimized. So, your guess at it being a resource issue could be the case.

Try using ModernHttpClient (Xamarin Component | Nuget | Developer Review | Github), and adding the NativeMessageHandler in the constructor for you HttpClient. This will use the some optimized native libraries (for Android, it's OkHttp) which will help with performance.