Skip to content

Commit 990d33e

Browse files
committed
Making connection thread safe
1 parent 8fab3b7 commit 990d33e

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Source/Clients/Connections/ChronicleConnection.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ public sealed class ChronicleConnection : IChronicleConnection, IChronicleServic
5151
readonly string? _certificatePassword;
5252
readonly ITokenProvider _tokenProvider;
5353
readonly bool _disableTls;
54+
readonly SemaphoreSlim _connectLock = new(1, 1);
5455
GrpcChannel? _channel;
5556
IConnectionService? _connectionService;
5657
DateTimeOffset _lastKeepAlive = DateTimeOffset.MinValue;
@@ -136,6 +137,7 @@ IServices IChronicleServicesAccessor.Services
136137
/// <inheritdoc/>
137138
public void Dispose()
138139
{
140+
_connectLock.Dispose();
139141
_channel?.Dispose();
140142
_keepAliveSubscription?.Dispose();
141143
if (_tokenProvider is IDisposable disposableTokenProvider)
@@ -152,6 +154,24 @@ public async Task Connect()
152154
return;
153155
}
154156

157+
await _connectLock.WaitAsync(_cancellationToken);
158+
try
159+
{
160+
if (Lifecycle.IsConnected)
161+
{
162+
return;
163+
}
164+
165+
await ConnectInternal();
166+
}
167+
finally
168+
{
169+
_connectLock.Release();
170+
}
171+
}
172+
173+
async Task ConnectInternal()
174+
{
155175
_logger.Connecting(_connectionString);
156176
_channel?.Dispose();
157177
_keepAliveSubscription?.Dispose();

0 commit comments

Comments
 (0)