Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Windows.Web.Http.HttpClient have to be disposed per HTTP request? [duplicate]

From this answer to the question: Do HttpClient and HttpClientHandler have to be disposed?, I see that the best practice is not to dispose a System.Net.Http.HttpClient per HTTP request. In particular, it is stated that:

standard usage of HttpClient is not to dispose of it after every request.

And that is fine.

My question is, does this "pattern" apply to Windows.Web.Http.HttpClient as well? Or should it be disposed per HTTP request? I think the documentation is a bit vague on this. In one of the samples, it simply states:

// Once your app is done using the HttpClient object call dispose to 
// free up system resources (the underlying socket and memory used for the object)
httpclient.Dispose();

I believe this can be read both ways, so any specific input on this is appreciated.

like image 663
Lasse Christiansen Avatar asked Sep 28 '22 09:09

Lasse Christiansen


1 Answers

It seems to me that if it were intended to be used for only one request at a time, it would simply throw an exception if you tried to use it for more than one.

Also, consider that all but the earliest version of HTTP allows multiple requests for a given TCP connection. Using the same HttpClient object allows the framework to maintain a TCP connection for multiple requests.

While it's true that the sample code performs just one request, note this text in the documentation:

The HttpClient class instance acts as a session to send HTTP requests and receive responses. An HttpClient instance is a collection of settings that apply to all requests executed by that instance. In addition, every HttpClient instance uses its own connection pool…

[emphasis mine]

For the object to act as "a collection of settings that apply to all requests executed by that instance", it is obvious it would have to be used for more than one request.

like image 132
Peter Duniho Avatar answered Oct 18 '22 02:10

Peter Duniho