public async Task HandleClient(CancellationToken cancellationToken, Client client) { Connection connection = await connectionService.NewConnection((IPEndPoint)client.TcpClient.Client.RemoteEndPoint); try { await using INetworkStreamWrapper networkStream = new NetworkStreamWrapper(client.TcpClient.GetStream()); await streamHandler.HandleStream(cancellationToken, client, networkStream); networkStream.Close(); } catch (Exception exception) { logger.LogCritical(exception, $"{client.Protocol}"); } finally { logger.LogDebug($"{client.Protocol}: disconnected {client.TcpClient.Client.RemoteEndPoint}"); client.TcpClient.Close(); await connectionService.MarkConnectionAsClosed(connection); } }