Skip to content

Commit

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

public class HttpClientFactory
{
private static readonly ConcurrentDictionary<string, HttpClient> _clients = new();

private HttpClientFactory()
{
}

public static HttpClient GetInstance(HttpClientConfig config)
{
// 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))
return createWebClient(config); // this is not best practice!!
/*
if (!_clients.ContainsKey(config.BaseUrl))
{
return newClient;
var client = createWebClient(config);
_clients[client.BaseAddress.ToString()] = client;
}
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;
return _clients[config.BaseUrl];
*/
}

/// <summary>
Expand Down

1 comment on commit e1160af

@Saibamen
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gdl-drw: Maybe try to use lock?

Please sign in to comment.