grimus
grimus

Reputation: 3175

How can I set maximum connections on BCL's HttpClient?

I am using the BCL version of HttpClient (available here) for use in a portable class library.

Is there a way to set the limit of maximum connections used by an instance of HttpClient?

One of the reasons I'm using HttpClient instead of HttpWebRequest is because in my situation, HttpWebRequest's connection limit of 2 is too low, and causing issues in the case of a purposely long running request. By using an instance of HttpClient per request I've got around this limitation, but now seems to be causing the opposite problem, in that the server is overwhelmed when there are a lot of requests all at once and resulting in exceptions being thrown by the HttpClient. So the ideal solution would be being able to set the number of connections used by HttpClient so that it's higher than 2, but less than infinite, and probably closer to 5.

Upvotes: 1

Views: 1955

Answers (2)

Claire Novotny
Claire Novotny

Reputation: 1701

If you use an adaptation/enlightenment pattern to create your HttpClient instances, you can do it.

In the .NET factory, you'd use the ServicePointManager. For WinRT, you could use my WinRtHttpClientHander:

https://github.com/onovotny/WinRtHttpClientHandler

It'll let you access an HttpBaseProtocolFilter instance where you can set the MaxConnectionsPerServer property: http://msdn.microsoft.com/en-us/library/windows/apps/windows.web.http.filters.httpbaseprotocolfilter.maxconnectionsperserver.aspx

Upvotes: 1

Darrel Miller
Darrel Miller

Reputation: 142174

HttpClient uses HttpWebRequest under the covers, so you set the connection limit in the same way.

    ServicePointManager.DefaultConnectionLimit = 10;

The weird thing is that even though this value has a default value of 2, if you don't set it explicitly, the default value is ignored, and so that's why you are seeing an unlimited amount of connections.

Upvotes: 1

Related Questions