How many HttpClients should I create?

Initially, my code created a new HttpClient in the using statement for each request. Then I read a few articles about reusing HttpClient for better performance.

Here is an excerpt from one such article:

I do not recommend creating an HttpClient inside the Using block to make a single request. When the HttpClient is deleted, it causes the connection to also be closed. This means that the next request is to reopen this connection. You should try and reuse your HttpClient instances.

http://www.bizcoder.com/httpclient-it-lives-and-it-is-glorious

It seems to me that leaving an open connection will be useful only if several requests in a row go to the same places - for example, www.api1.com.

My question is: how can I create HttpClients?

My site talks about ten different services on the back.

Should I create one HttpClient for all of them, or should I create a separate HttpClient for each domain that I use on the back panel?

Example: If I talk with www.api1.com and www.api2.com, should I create 2 different HttpClients or only one HttpClient?

+3
source share
1 answer

Indeed, disposing of HttpClient will not force the closure of the main TCP / IP connection from the connection pool. Your best performance scenario is what you suggested:

  • Save an instance of HttpClient for each internal service with which you need to connect or the lifetime of your application.

  • , , API . (API .)

+1

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


All Articles