Change generated clients to be noob-safe in how they use HttpClient
#1,097 建立於 2017年12月11日
倉庫指標
- Star
- (6,291 star)
- PR 合併指標
- (30 天內沒有已合併 PR)
描述
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. ...
- Make your HttpClient static.
- 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).