0

I have read many documents and i saw many examples. But i didn't manage to understand exactly which is the proper way to use httpclient. My aplication uses httpclient multiple times in different threads and in different urls, and in most cases at the same time. Till now i am using httpclient as example below for each of my request.

using(var client = new HttpClient())
{
    client.TimeOut = TimeSpan.FromSeconds(20);
    var result = await client.GetAsync(www.mysite.com);
}

As Microsoft's documentation says "HttpClient is intended to be instantiated once per application, rather than per-use" Can i use a static instance of httpclient? Then to make a request without to affect an already active 'GET' request? Is it better by this way? Could please someone clarify me this?

I am using a winform application and a xamarin application.

9
  • Disposing HttpClient forces all tcp connections to close. Keeping it alive will perform better for multiple requests to the same server. Commented Jun 15, 2021 at 6:46
  • The recommendation is to in fact one single instance. Either through explicitly constructing one or (which I'd prefer) through IHttpClientFactory. But all of which also depends on what project type. Are you in a console app? Commented Jun 15, 2021 at 6:47
  • Will i have any problem if i will make three requests in same time with different urls and timeouts? Commented Jun 15, 2021 at 6:48
  • @Fildor no i am using a winform application and a xamarin application Commented Jun 15, 2021 at 6:49
  • 1
    It's explicitly documented that the various methods that send requests are thread safe. Commented Jun 15, 2021 at 6:50

1 Answer 1

1

You're correct you should make a single instance of the HttpClient for your application and use it in each of your threads. A popular way to do this is to use the Singleton pattern.

The case where you'd have multiple HttpClient instances in the same application would be if you want them to behave differently, for example you might want one that has a cookie store and one without.

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

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.