Reputation: 47
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.
Upvotes: 0
Views: 1611
Reputation: 382
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.
Upvotes: 1