in DeviceBridge/Services/ConnectionManager.cs [323:388]
public async Task AssertDeviceConnectionClosedAsync(string deviceId, bool temporary = false)
{
_logger.Info("Attempting to tear down {connectionType} connection for device {deviceId}", temporary ? "Temporary" : "Permanent", deviceId);
var mutex = _clientSemaphores.GetOrAdd(deviceId, new SemaphoreSlim(1, 1));
await mutex.WaitAsync();
try
{
_logger.Info("Acquired connection lock for device {deviceId}", deviceId);
// Attempt to remove the permanent or temporary connection from the list
if (temporary)
{
var currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
if (_hasTemporaryConnectionUntil.TryGetValue(deviceId, out long shouldLiveUntil))
{
if (currentTime > shouldLiveUntil)
{
_hasTemporaryConnectionUntil.TryRemove(deviceId, out _);
}
else
{
_logger.Info("Attempted to tear down temporary connection for device {deviceId}, but connection has not yet expired", deviceId);
return;
}
}
else
{
_logger.Info("Attempted to tear down temporary connection for device {deviceId}, but a temporary connection wasn't found", deviceId);
return;
}
}
else
{
if (!_hasPermanentConnection.TryRemove(deviceId, out _))
{
_logger.Info("Attempted to tear down permanent connection for device {deviceId}, but a permanent connection wasn't found", deviceId);
return;
}
}
// Do not actually close client if a permanent or temporary connection still exists.
if (_hasPermanentConnection.TryGetValue(deviceId, out _) || _hasTemporaryConnectionUntil.TryGetValue(deviceId, out _))
{
_logger.Info("Attempted to tear down connection for device {deviceId}, but a permanent or temporary connection for this device still exists.", deviceId);
return;
}
if (!_clients.TryRemove(deviceId, out DeviceClient client))
{
_logger.Info("Connection for device {deviceId} doesn't exist", deviceId);
return;
}
await client.CloseAsync();
client.Dispose();
client.SetConnectionStatusChangesHandler(null);
_logger.Info("Closed connection for device {deviceId}", deviceId);
}
finally
{
mutex.Release();
}
}