I've got this method and I realize that an instance of HttpClass
is going to be created for each call to it. While working seemingly OK, I'm considering moving it out and placing it as a private property accessible to each call to the method. There might be other methods making use of it in the future as well. I have no information on how often these calls will occur. (There's a try
/catch
too but it's omitted for brevity's sake.)
[OperationContract]
[WebGet(UriTemplate = "Poof"]
public async Task<String> GetPoof()
{
String url = BaseUrl + "poofy";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.TryAddWithoutValidation(
"Authorization", GetAuthorizationSchema());
HttpResponseMessage message = await client.GetAsync(url);
return await message.Content.ReadAsStringAsync();
}
}
What I'm thinking of is something like this:
private HttpClient _Client
private HttpClient Client { get { return _Client ?? GetNewClient(); } }
[OperationContract]
[WebGet(UriTemplate = "Poof"]
public async Task<String> GetPoof()
{
String url = BaseUrl + "poofy";
HttpResponseMessage message = await client.GetAsync(url);
return await message.Content.ReadAsStringAsync();
}
My worry is, though, that the different calls utilizing the same client instance will somehow collide and call huge issues later on, especially if the number of calls per time unit raises beyond a critical level. Should I be worried?
2 Answers 2
You don't need multiple instances. In fact, HttpClient
is designed specifically to persist and be used for multiple requests (see: HttpClient.DefaultRequestHeaders
).
There's already a lot written about this so I'll redirect you to those resources:
-
\$\begingroup\$ Another link worth reading: YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE \$\endgroup\$marbel82– marbel822021年10月21日 12:56:53 +00:00Commented Oct 21, 2021 at 12:56
I suggest
private HttpClient Client { get { return _Client = _Client ?? GetNewClient(); } }
Instead of
private HttpClient Client { get { return _Client ?? GetNewClient(); } }
-
\$\begingroup\$ This spells out how to exploit HttpClient safe to use concurrently - as opposed to trying. \$\endgroup\$greybeard– greybeard2018年03月07日 05:39:46 +00:00Commented Mar 7, 2018 at 5:39
-
\$\begingroup\$ Actually, I prefer to use an static HttpClient variable and the initialization inside the static constructor of the main class \$\endgroup\$Moisés Alexander Salazar Vila– Moisés Alexander Salazar Vila2018年03月07日 10:41:33 +00:00Commented Mar 7, 2018 at 10:41