1

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Isn't this a dangerous answer? Its my understanding that calling HttpClient privately is not thread-safe? My understanding is you either call it statically or at a class level but always publicly.
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.