Is a singleton a good way of instantiating a HttpClient

最后都变了- 提交于 2019-12-12 03:09:10

问题


I have a C# library that makes calls to a restful web service using a HttpClient.

The class library is used inside an MVC application that could run for weeks without being restarted.

Is a singleton a good way of creating the HttpClient so I have just one HttpClient for the very long life of the MVC application?


回答1:


I singleton would keep the HttpClient for the life of the application, but I would ask why you want to do that. It is not good practice.

HttpClient implements IDisposable, really it should be disposed after you have used it. A using statement would be an easy way to do that:

using (var client = new HttpClient()) 
{
  // Do something
}

This way you can be sure your resources are all cleaned up when you don't need them. Instantiating a new HttpClient is not particularly expensive, so it would not affect the applications performance.




回答2:


Please look at Is HttpClient safe to use concurrently?

Here is another article from Henrik F. Nielsen about HttpClient where he says:

"The default HttpClient is the simplest way in which you can start sending requests. A single HttpClient can be used to send as many HTTP requests as you want concurrently so in many scenarios you can just create one HttpClient and then use that for all your requests."

So you can use a singleton with HttpClient if you will use asynchronous methods, like:

CancelPendingRequests
DeleteAsync
GetAsync
GetByteArrayAsync
GetStreamAsync
GetStringAsync
PostAsync
PutAsync
SendAsync

Quick summary:

  • If you have requests that are related (or won't step on eachother) then using the same HttpClient makes a lot of sense.
  • In genral I would recommend reusing HttpClient instances as much as possible.


来源:https://stackoverflow.com/questions/37143162/is-a-singleton-a-good-way-of-instantiating-a-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!