HttpClientHelper

using System; using System.Net.Http; // Thread-safe singleton. internal sealed class HttpClientHelper : IDisposable { #region Declares // Single instance of the HttpClient. private HttpClient httpClient; // Thread syncronization object. private readonly object syncObject = new object(); // Singleton instance. public static readonly HttpClientHelper Instance = new HttpClientHelper(); #endregion #region Constructor // Singleton constructor. private HttpClientHelper() { } #endregion #region GetHttpClient // Creates or retrieve the single instance of the HttpClient. public HttpClient GetHttpClient(HttpMessageHandler handler = null) { if (this.httpClient == null) { lock (this.syncObject) { if (this.httpClient == null) { if (handler == null) { this.httpClient = new HttpClient(); } else { this.httpClient = new HttpClient(handler); } } } } return this.httpClient; } #endregion #region IDisposable // Cleans up the stuff. public void Dispose() { if (this.httpClient != null) { this.httpClient.Dispose(); this.httpClient = null; } } #endregion }
This is a very simplistic way to use the same instance of the HttpClient across all the application.
I use it internal, but you may change to public if necessary.

In case you do not know, the HttpClient (unlike the DbConnection, for example) is the connection pool itself: if you create an instance of the HttpClient each time you need to use the HttpClient, you are wasting sockets and you might (in an extreme scenario) run out of sockets in the server in which your application is running.

Official documentation for HttpClient: https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx
"HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors."

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.