Hi All,
I have read so many articles on HttpClient. In some articles, it is mentioned to create single instance of httpclient and reuse it in the entire application. But in some articles it is mentioned to create new instance of httpclient per webrequest.
**
using(var httpClient = new HttpClient())
{
}
Could you please let me know which approach is the better?
I have created a small POC. Test 1 : Single instance of httpclient.
private static readonly HttpClient _httpClient = new HttpClient();
private const string ServerGetUrl = "http://localhost:80/api/service/getdata";
private static void TestPingWithSingleInstance()
{
Parallel.For(0, 5,
i =>
{
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = _httpClient.GetAsync(ServerGetUrl).GetAwaiter().GetResult();
var data = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
Console.WriteLine(data);
Console.WriteLine("===============");
});
}
When I fired netstat command. It displays 5 open ports.
TCP 127.0.0.1:46336 DESKTOP-OEOGI0L:http ESTABLISHED
TCP 127.0.0.1:46337 DESKTOP-OEOGI0L:http ESTABLISHED
TCP 127.0.0.1:46338 DESKTOP-OEOGI0L:http ESTABLISHED
TCP 127.0.0.1:46339 DESKTOP-OEOGI0L:http ESTABLISHED
TCP 127.0.0.1:46340 DESKTOP-OEOGI0L:http ESTABLISHED
Test 2 : Create instance per webrequest.
private static void TestPingWithDisposableInstance()
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = httpClient.GetAsync(ServerGetUrl).GetAwaiter().GetResult();
var data = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
Console.WriteLine(data);
Console.WriteLine("===============");
}
}
When I fired netstat command. It displays 5 open ports.
TCP 127.0.0.1:46233 DESKTOP-OEOGI0L:http TIME_WAIT
TCP 127.0.0.1:46234 DESKTOP-OEOGI0L:http TIME_WAIT
TCP 127.0.0.1:46235 DESKTOP-OEOGI0L:http TIME_WAIT
TCP 127.0.0.1:46236 DESKTOP-OEOGI0L:http TIME_WAIT
TCP 127.0.0.1:46237 DESKTOP-OEOGI0L:http TIME_WAIT
Same numbers of ports will be open if we use single instance or instance per webrequest. Could you please let me know the better approach ?
Note : I am using .Net 4.5.1 framework.
Thanks in advance.
What I have tried:
I have created a above POC. Same number of ports open for both the approaches.