public async Task SetMethodCallbackAsync()

in DeviceBridge/Services/ConnectionManager.cs [615:649]


        public async Task SetMethodCallbackAsync(string deviceId, string id, MethodCallback callback)
        {
            _logger.Info("Attempting to set method handler for device {deviceId}", deviceId);

            if (callback == null)
            {
                throw new ArgumentNullException(nameof(callback));
            }

            // We need to synchronize this with client creation/close so a race condition doesn't cause us to miss the
            // callback registration on a client that is being currently created.
            var mutex = _clientSemaphores.GetOrAdd(deviceId, new SemaphoreSlim(1, 1));
            await mutex.WaitAsync();

            try
            {
                _logger.Info("Acquired connection lock for device {deviceId}", deviceId);

                // Save the callback so it can be registered whenever a client is created
                _methodCallbacks.AddOrUpdate(deviceId, (id, callback), (key, oldValue) => (id, callback));

                // If a client currently exists, register the callback
                if (!_clients.TryGetValue(deviceId, out DeviceClient client))
                {
                    _logger.Info("Connection for device {deviceId} not found while trying to set method callback. Callback will be registered whenever a new client is created", deviceId);
                    return;
                }

                await client.SetMethodDefaultHandlerAsync(callback, null);
            }
            finally
            {
                mutex.Release();
            }
        }