From e0b48b3b7c31674f66da7728c3f000766729cd4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Rei=C3=9F-W=C3=B6ltche?= Date: Thu, 7 Nov 2024 11:22:19 +0100 Subject: [PATCH] Optimize HttpClient reuse to prevent redundant instances --- .../HttpClientFactory.cs | 29 ++++++++++++++----- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/Gandalan.IDAS.WebApi.Client/HttpClientFactory.cs b/Gandalan.IDAS.WebApi.Client/HttpClientFactory.cs index 0189e840..fe7c3771 100644 --- a/Gandalan.IDAS.WebApi.Client/HttpClientFactory.cs +++ b/Gandalan.IDAS.WebApi.Client/HttpClientFactory.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Net; using System.Net.Http; @@ -52,21 +53,35 @@ public object Clone() public class HttpClientFactory { + private static readonly ConcurrentDictionary _clients = new(); + private HttpClientFactory() { } public static HttpClient GetInstance(HttpClientConfig config) { - return createWebClient(config); // this is not best practice!! - /* - if (!_clients.ContainsKey(config.BaseUrl)) + // Check if an instance already exists to avoid unnecessary creation + if (_clients.TryGetValue(config.BaseUrl, out var client)) + { + return client; + } + + // Try to add a new client; only one thread will succeed in adding + var newClient = createWebClient(config); + if (_clients.TryAdd(config.BaseUrl, newClient)) { - var client = createWebClient(config); - _clients[client.BaseAddress.ToString()] = client; + return newClient; } - return _clients[config.BaseUrl]; - */ + else + { + // Dispose the newly created client if another thread added a client first + newClient.Dispose(); + } + + // Retrieve the existing client from the dictionary + _clients.TryGetValue(config.BaseUrl, out client); + return client; } ///