Last active
February 8, 2019 23:16
-
-
Save christo8989/cb1f30bd775d153044708aaa6ce79f8d to your computer and use it in GitHub Desktop.
HttpClients are difficult to use in C#. This class will manage them for you.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var url = "https://api.test.com/api/test/1"; | |
var client = HttpClientManager.Get(url); | |
var value = await client.GetAsync(url); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://www.tomdupont.net/2014/11/net-45-httpclient-is-thread-safe.html | |
// http://www.nimaara.com/2016/11/01/beware-of-the-net-httpclient | |
public static class HttpClientManager | |
{ | |
private static readonly ConcurrentDictionary<string, HttpClient> clients = new ConcurrentDictionary<string, HttpClient>(); | |
private static readonly object lockobj = new Object(); | |
public static HttpClient Get(string url) | |
{ | |
return Get(url, (uri) => new HttpClient()); | |
} | |
public static HttpClient Get(string url, Func<Uri, HttpClient> createClient) | |
{ | |
var numberOfClients = clients.Count; | |
if (numberOfClients < 1) | |
{ | |
ServicePointManager.DnsRefreshTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; | |
} | |
var uri = GetBaseUri(url); | |
var key = uri.Authority; | |
if (!clients.TryGetValue(key, out var client)) | |
{ | |
lock (lockobj) | |
{ | |
if (!clients.TryGetValue(key, out client)) | |
{ | |
client = clients.GetOrAdd(key, createClient(uri)); | |
ServicePointManager.FindServicePoint(uri).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds; | |
} | |
} | |
} | |
return client; | |
} | |
private static Uri GetBaseUri(string url) | |
{ | |
var wholeUri = new Uri(url); | |
var baseString = $"{wholeUri.Scheme}://{wholeUri.Authority}"; | |
var baseUri = new Uri(baseString); | |
return baseUri; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment