Skip to content

Commit

Permalink
Minor lock cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesNK committed Apr 29, 2024
1 parent c622b5a commit 4201eff
Showing 1 changed file with 24 additions and 22 deletions.
46 changes: 24 additions & 22 deletions src/Grpc.Net.Client/Balancer/Subchannel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#endregion

#if SUPPORT_LOAD_BALANCING
using System.Diagnostics;
using System.Net;
using Grpc.Core;
using Grpc.Net.Client.Balancer.Internal;
Expand Down Expand Up @@ -214,7 +215,10 @@ public void UpdateAddresses(IReadOnlyList<BalancerAddress> addresses)

if (requireReconnect)
{
CancelInProgressConnect();
lock (Lock)
{
CancelInProgressConnectUnsynchronized();
}
_transport.Disconnect();
RequestConnection();
}
Expand Down Expand Up @@ -269,33 +273,31 @@ public void RequestConnection()
}
}

private void CancelInProgressConnect()
private void CancelInProgressConnectUnsynchronized()
{
lock (Lock)
{
if (_connectContext != null && !_connectContext.Disposed)
{
SubchannelLog.CancelingConnect(_logger, Id);
Debug.Assert(Monitor.IsEntered(Lock));

// Cancel connect cancellation token.
_connectContext.CancelConnect();
_connectContext.Dispose();
}
if (_connectContext != null && !_connectContext.Disposed)
{
SubchannelLog.CancelingConnect(_logger, Id);

_delayInterruptTcs?.TrySetResult(null);
// Cancel connect cancellation token.
_connectContext.CancelConnect();
_connectContext.Dispose();
}

_delayInterruptTcs?.TrySetResult(null);
}

private ConnectContext GetConnectContext()
private ConnectContext GetConnectContextUnsynchronized()
{
lock (Lock)
{
// There shouldn't be a previous connect in progress, but cancel the CTS to ensure they're no longer running.
CancelInProgressConnect();
Debug.Assert(Monitor.IsEntered(Lock));

var connectContext = _connectContext = new ConnectContext(_transport.ConnectTimeout ?? Timeout.InfiniteTimeSpan);
return connectContext;
}
// There shouldn't be a previous connect in progress, but cancel the CTS to ensure they're no longer running.
CancelInProgressConnectUnsynchronized();

var connectContext = _connectContext = new ConnectContext(_transport.ConnectTimeout ?? Timeout.InfiniteTimeSpan);
return connectContext;
}

private async Task ConnectTransportAsync()
Expand All @@ -310,7 +312,7 @@ private async Task ConnectTransportAsync()
return;
}

connectContext = GetConnectContext();
connectContext = GetConnectContextUnsynchronized();

// Use a semaphore to limit one connection attempt at a time. This is done to prevent a race conditional where a canceled connect
// overwrites the status of a successful connect.
Expand Down Expand Up @@ -522,7 +524,7 @@ public void Dispose()

lock (Lock)
{
CancelInProgressConnect();
CancelInProgressConnectUnsynchronized();
_transport.Dispose();
_connectSemaphore.Dispose();
}
Expand Down

0 comments on commit 4201eff

Please sign in to comment.