Skip to content

Commit

Permalink
Optimize HttpClient reuse to prevent redundant instances
Browse files Browse the repository at this point in the history
  • Loading branch information
gdl-drw committed Nov 7, 2024
1 parent f854609 commit e0b48b3
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions Gandalan.IDAS.WebApi.Client/HttpClientFactory.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
Expand Down Expand Up @@ -52,21 +53,35 @@ public object Clone()

public class HttpClientFactory
{
private static readonly ConcurrentDictionary<string, HttpClient> _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;
}

/// <summary>
Expand Down

0 comments on commit e0b48b3

Please sign in to comment.