简体   繁体   中英

Performance Issue: .NET HttpClient Response is slow

Problem:

I am using .NET Class HttpClient to make Requests to the endpoint URL.

My Code:

using (HttpClient apiClient1 = new HttpClient())
{
    apiClient.GetAsync(apiUrl).Result;
}

Problem Identified:

If I use using block, I'm opening multiple connections, leads to socketExceptions .

Changed My Above Code to:

public class RequestController: ApiController
{
    private static HttpClient apiClient = new HttpClient();

    [HttpPost]
    public  dynamic GetWebApiData([FromBody] ParamData params)
    {
           var resultContent = apiClient.GetAsync(apiUrl).Result.Content;
           return Newtonsoft.Json.JsonConvert.DeserializeObject<object>(resultContent.ReadAsStringAsync().Result);
    }
}

Result of the above code after making HttpClient as static is as follows:

  1. Only one Connection is established.

  2. For Each request, I'm looking for the 200 milliseconds reduction in Response Time.

What I Need:

I want to make conurrent calls atleast 50 calls to the end point with High-Speed response.

Kindly help me with this scenario.

Use the async API and stop calling .Result blocking calls.

public class RequestController: ApiController {
    private static HttpClient apiClient = new HttpClient();

    [HttpPost]
    public async Task<IHttpActionResult> GetWebApiData([FromBody] ParamData data) {
        var response = await apiClient.GetAsync(apiUrl);
        var resultContent = response.Content;
        var model = await resultContent.ReadAsAsync<dynamic>();
        return Ok(model);
    }
}

The default SSL connection idle timeout of HttpClient are 2 mins. So, after that you have to re handshake with the server. This maybe the root cause.

You could follow this article( https://www.stevejgordon.co.uk/httpclient-connection-pooling-in-dotnet-core ) to extend the timeout. But the testing result from my side, I could only extend to 5 mins. After that, the connection will be closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM