Why HttpClient create only two connections for several requests for one domain at a time? For example, such a code

 static string[] urls = new string[] { "http://site.com/a", "http://site.com/b", "http://site.com/c", "http://site.com/d", }; static void Main() { var hc = new HttpClient(); var list = new List<Task<string>>(); foreach (var item in urls) { list.Add(hc.GetStringAsync(item)); } Task.WaitAll(list.ToArray()); } 

will lead to this result two connections

because of which the whole process will be slower, as it is necessary to wait for the completion of any of the two requests to start the third

Although if you change requests to different domains

 static string[] urls = new string[] { "http://sitea.com/", "http://siteb.com/", "http://sitec.com/", "http://sited.com/", }; 

then

fine

Why is this happening, why only two at the same time, how to solve it?

  • @PrimusSingularis, I can not understand how the creation of many HttpClient 's then helps? - Qutrix
  • @Qutrix most likely creating a new HttpClient causes garbage collection and dispose of old HttpClient (disposes them by the way) - PashaPash
  • @PashaPash, I don’t really understand how this is connected - Qutrix
  • @Qutrix vrodeba before setting from ServicePointManager limited the total number of connections, and not just from one HttpClient. I could well be wrong. - PashaPash

2 answers 2

Try changing the value of ServicePointManager.DefaultConnectionLimit

Managing connections

  • Yes, it worked, but the question remained: how then does the creation of many HttpClient 's HttpClient ? - Qutrix
  • @Qutrix restriction works for one client, about why this is done, you can read the discussion here github.com/dotnet/corefx/issues/2332 , as for RFC 2616 - Primus Singularis

According to MSDN, the problem is that OS WINDOWS itself limits the number of simultaneous requests for services based on HTTP 1.0 to 4 pieces and on HTTP 1.1 to two pieces.

To fix this situation, you need to go to the register (Win + R -> regedit) Find the branch HKEY_CURRENT_USER \ Software \ Microsoft \ Windows \ CurrentVersion \ Internet Settings

and add two variables (or change the available ones)

MaxConnectionsPerServer = for http 1.1 and MaxConnectionsPer1_0Server for http 1.0, which are set to 2 and 4, respectively.

  • changed, launched - did not help, everything is the same 2. And it does not seem that the problem is this, since if you make a lot of HttpClient 's, then there will be many simultaneous connections even for one domain - Qutrix