Reputation: 8242
I am recreating an instance of HttpClient
in each of my static request methods but have read that it is preferable (in most situations) to reuse an HttpClient
instance.
What is the preferred/recommended way to reuse HttpClient
instances in a static class?
Upvotes: 1
Views: 4571
Reputation: 452
My understanding is that you can initialise HTTP Client and reuse that instance as long as you call it publicly it will be thread-safe see he thread safety section here https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.dnsrefreshtimeout(v=vs.110).aspx If you create a new HTTPClient call each time all you are doing is opening up multuiple sockets. This post (and the associated comments) tackles the topic very succinctly. https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
Upvotes: 0
Reputation: 437424
Since your request methods are static, the HttpClient
must also be a static
member of the class in order to be reused (or some moral equivalent).
You could also decide to add more abstraction here, e.g. instead of grabbing a static
field use a private static
getter method; this allows you to centrally decide if the HttpClient
should be reused or another instance returned on a per-call basis.
Upvotes: 1