Using the .NET HttpClient class wrongly can destabilize software
aspnetmonsters.com
aspnetmonsters.com
"Do not initialize unnecessarily" is a pretty common paradigm in .NET this extends way beyond variables and constructors. Even if the HttpClient did not cause this http.sys/winsock errata there is still absolutely no reason to initialize a new instance of it within a loop you are wasting CPU time and more importantly memory and leaving your garbage collector extra work.
Idealy a loop should not really initialize or create any new objects, create what you need an access it from within the loop, initializing a new instance of a class in every cycle of the loop, creating new variables, subscribing to event handlers etc. is just really really bad coding practice and this is basic .NET performance practices.
The "lesson" the author should've learned isn't that HttpClient is designed oddly, or that there are some oddities with how Windows handles sockets, but that "var foo = new bar()" and the likes do not belong inside a loop or any other iterative statement unless there is absolutly no other way of doing without it (and I can't think of a scenario in which that would be the case).
https://en.m.wikipedia.org/wiki/HTTP_pipelining
Have it sitting in the background waiting for the controller to ask it to do something, you can manage the sockets and you can make a request queue on your end if you getting into resource cap issues.
IDisposable kind of sucks. Unless you know the inner workings of whatever implements it, it's hard to know how to handle lifecycles and how important properly disposing is. Is it wrapping a heavyweight COM object that is going to leak memory badly? Is it going to tie up limited system resources? Or is it a lightweight .NET object that someone has abused the interface to perform some trivial cleanup operations? There's no real guarantees.
In a typical usage scenario in an async Task, this is what it'd look like:
using (var response = await _httpClient.GetAsync(requestUri))
{
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Foo>(result);
}I've not found a drawback and found it shortened my code. Only downside is the extra indentation.
The original article just pointed out a basic coding flaw of having new within a loop. The using wasn't the bad part.
We changed the title in an attempt to make it more accurate and neutral.