RicoSuter/NSwag

Change generated clients to be noob-safe in how they use HttpClient

Open

#1,097 opened on Dec 11, 2017

View on GitHub
 (22 comments) (4 reactions) (0 assignees)C# (1,189 forks)batch import
help wantedtype: discussion

Repository metrics

Stars
 (6,291 stars)
PR merge metrics
 (No merged PRs in 30d)

Description

Edit So I had some noob misunderstanding in HttpClient best practice.

  • Some Microsoft sources say you should keep a static HttpClient forever, to avoid socket exhaustion
  • Others point out that, no, holding sockets forever is bad (for instance if you are using load balancing) so you should recycle your HttpClient now and then, (just not on every request)

I appreciate you have added stuff for control of HttpClient lifecycle, but perhaps you can make this safe out of the box? Noobs like me might also learn something by reviewing the generated code.

Here is one approach: https://github.com/dotnet/corefx/issues/11224#issuecomment-347361456


Original comments...

According to https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

After each call, even though you've disposed the HttpClient, Windows holds the socket(s) it was using open for 240 seconds. There are only thousands of sockets available, so you can achieve socket exhaustion quite easily.

Although [HttpClient] implements the IDisposable interface it is actually a shared object. This means that under the covers it is reentrant) and thread safe. Instead of creating a new instance of HttpClient for each execution you should share a single instance of HttpClient for the entire lifetime of the application. ...

  1. Make your HttpClient static.
  2. Do not dispose of or wrap your HttpClient in a using unless you explicitly are looking for a particular behaviour (such as causing your services to fail).

Contributor guide