c# – Xamarin.Android HTTP随机延迟

我有一个方法执行多个HTTP请求,称为LoadServers()一个执行LoadServers()的按钮.对于我的问题,我只在前一次LoadServers()调用完成后点击按钮.加载时会出现一个进度对话框,所以我只能连续执行它们.

一旦大约每10-15次调用LoadServers就会导致第一个http请求延迟几乎整整10秒. LoadServers完成的平均时间不到半秒,从不超过1秒.这只发生在Xamarin.Android上. Xamarin.iOS上不会发生延迟,所有这些代码都是共享的.

这是我的代码

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);
    }
}

每15次执行LoadServers()会导致以下日志语句:

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)

这是否与HTTP请求的资源消耗有关?它会尝试清理资源并暂停执行,直到发生这种情况?我不确定执行请求时到底发生了什么.它会启动一个新线程吗?

最佳答案 弄清楚确切的问题很难,我无法重现它.但是,HttpClient中的System.Net和默认MessageHandler的包装并未完全优化.所以,你猜测它是一个资源问题可能就是这样.

尝试使用ModernHttpClient(Xamarin Component | Nuget | Developer Review | Github),并在构造函数中为HttpClient添加NativeMessageHandler.这将使用一些优化的本机库(对于Android,它是OkHttp),这将有助于提高性能.

点赞