mirror of
https://github.com/gnh1201/welsonjs.git
synced 2025-11-29 02:50:48 +00:00
Serialize connection creation per key
This commit is contained in:
parent
b8362e570c
commit
c7890aaadb
|
|
@ -22,6 +22,8 @@ namespace WelsonJS.Launcher
|
||||||
{
|
{
|
||||||
private readonly ConcurrentDictionary<string, (TConnection Connection, TParameters Parameters)> _pool
|
private readonly ConcurrentDictionary<string, (TConnection Connection, TParameters Parameters)> _pool
|
||||||
= new ConcurrentDictionary<string, (TConnection, TParameters)>();
|
= new ConcurrentDictionary<string, (TConnection, TParameters)>();
|
||||||
|
private readonly ConcurrentDictionary<string, SemaphoreSlim> _openLocks
|
||||||
|
= new ConcurrentDictionary<string, SemaphoreSlim>();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Creates a unique cache key for the given connection parameters.
|
/// Creates a unique cache key for the given connection parameters.
|
||||||
|
|
@ -61,11 +63,28 @@ namespace WelsonJS.Launcher
|
||||||
return existing.Connection;
|
return existing.Connection;
|
||||||
}
|
}
|
||||||
|
|
||||||
RemoveInternal(key, existing.Connection);
|
var gate = _openLocks.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));
|
||||||
|
await gate.WaitAsync(token).ConfigureAwait(false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_pool.TryGetValue(key, out existing) && IsConnectionHealthy(existing.Connection))
|
||||||
|
{
|
||||||
|
return existing.Connection;
|
||||||
|
}
|
||||||
|
|
||||||
var connection = await OpenConnectionAsync(parameters, token).ConfigureAwait(false);
|
if (existing.Connection != null && !IsConnectionHealthy(existing.Connection))
|
||||||
_pool[key] = (connection, parameters);
|
{
|
||||||
return connection;
|
RemoveInternal(key, existing.Connection);
|
||||||
|
}
|
||||||
|
|
||||||
|
var connection = await OpenConnectionAsync(parameters, token).ConfigureAwait(false);
|
||||||
|
_pool[key] = (connection, parameters);
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
gate.Release();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user