问题
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