.NET Web API client: the best life cycle of the httpclient instance
.NET Web API client often interacts with multiple API -end points. A common problem is the best life cycle about the HTTPClient instance: Should share an instance for multiple calls, or create a new instance for each call?
The advantages of sharing the HTTPClient instance
Create a single HTTPClient instance and reuse it in multiple calls to have the following advantages:
credentials and Cookie:
HTTPClienthandler Maintenance credentials and cookies, these credentials and cookies are designed to reuse them across. Re -instantiated HTTPClient needs to reset these values.
- Custom default header: defaultRequestHeaders property storage is stored in a customized header that is used in multiple requests. Resetting them in each request will destroy their purpose.
httpmessagehandler: - HTTPClient support to add httpmessagehandler to the request/response pipe, for cross -sectional attention points (for example, log records, chipping). Reusable HTTPCLIENT can ensure that these processing programs are always applied.
The overhead of the HTTPClient instance alone -
Although there are many advantages to share the HTTPClient instance, it will also generate overhead when dealing with the instance:
TCP/IP connection Turn off: HTTPClient will also process its HTTPClientHandler, which will be forced to close the TCP/IP connection maintained by the servicepointManager. Create a new HTTPClient for each request to be re -established.
Performance considerations
- The performance of the use of the HTTPClient instance in a single time depends on factors such as network types and protocols:
LAN (LAN) uses HTTP:
Due to the underlying TCP guarantee mechanism, performance loss can be ignored.
The Internet uses http: Due to the re -establishment of the connection, 40% of performance losses were observed.
HTTPS connection:
When using https, the impact is expected to be greater.
-
Suggestion
- Based on these considerations, the best practice is to maintain an HTTPClient instance for the only API for each connection, so that it is the same as the life cycle of the application . This balances the advantages of reusable credentials, heads and processing programs, as well as the overhead of the creation and processing HTTPClient instance.
The above is the detailed content of Should I Reuse a Single HttpClient Instance or Create a New One for Each Web API Call?. For more information, please follow other related articles on the PHP Chinese website!