Why does HttpClient disable sockets?

When creating, using and deleting several HttpClients, I notice that there are open sockets in the TIME_WAIT status.

For example, after starting, do the following:

using System.Net.Http; namespace HttpClientTest { public class Program { public static void Main(string[] args) { for (var i = 0; i < 10; i++) { using (var httpClient = new HttpClient()) { var result = httpClient. GetAsync("http://stackoverflow.com/"). Result; } } } } } 

I see with netstat that sockets remain open:

 TCP 10.200.60.168:2722 151.101.193.69:http TIME_WAIT TCP 10.200.60.168:2751 151.101.193.69:http TIME_WAIT TCP 10.200.60.168:2752 151.101.193.69:http TIME_WAIT TCP 10.200.60.168:2753 151.101.193.69:http TIME_WAIT TCP 10.200.60.168:2754 151.101.193.69:http TIME_WAIT TCP 10.200.60.168:2755 151.101.193.69:http TIME_WAIT TCP 10.200.60.168:2756 151.101.193.69:http TIME_WAIT TCP 10.200.60.168:2757 151.101.193.69:http TIME_WAIT TCP 10.200.60.168:2758 151.101.193.69:http TIME_WAIT TCP 10.200.60.168:2759 151.101.193.69:http TIME_WAIT 

Is this the expected behavior? Is it necessary to explicitly specify the value of the connection header so that it does not close?

 httpClient. DefaultRequestHeaders. Connection. Add("close"); 
+5
source share
2 answers

Each instance of HttpClient combines its connections for better performance, but this means that each instance also leaves the joined connections at TIME_WAIT when not in use.

HttpClient actually thread safe, reentrant, and designed for extended use; it should not be deleted (although it implements IDisposable ) until your program exits. You must share one instance of HttpClient throughout the application to take advantage of this.

More information can be found here .

+6
source

From MSDN

each HttpClient instance uses its own connection pool, isolating its requests from requests made by other HttpClient instances.

HttpClient combines connections for better performance.

+1
source

Source: https://habr.com/ru/post/1257350/


All Articles