private async Task ListenChannelAsync(IServerChannel channel, CancellationToken cancellationToken) { var node = channel.RemoteNode; var senderChannel = new SenderChannelAdapter(channel); _channelProvider.AddChannel(node, senderChannel); using var listener = CreateChannelListener(senderChannel); var sessionTask = channel.ReceiveFinishingSessionAsync(cancellationToken); listener.Start(channel); try { await Task.WhenAny( sessionTask, listener.CommandListenerTask, listener.MessageListenerTask, listener.NotificationListenerTask); } finally { listener.Stop(); _channelProvider.RemoveChannel(node); await _options.Value.UnregistrationHandler( node, channel, cancellationToken.IsCancellationRequested?default: cancellationToken); } if (sessionTask.IsCompleted && channel.Transport.IsConnected) { using var cts = new CancellationTokenSource(_options.Value.CloseTimeout); await channel.SendFinishedSessionAsync(cts.Token); } }