public async Task StopAsync(CancellationToken cancellationToken) { if (_channelListener == null) { throw new InvalidOperationException("The client is not started"); } await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { _isStopping = true; _channelListener?.Stop(); await _onDemandClientChannel.FinishAsync(cancellationToken).ConfigureAwait(false); _channelListener = null; } catch (Exception ex) { _logger.Error(ex, $"An error ocurred while stopping the client: {ex.Message}"); throw; } finally { _semaphore.Release(); } }