private async Task HandleClientAsync(TcpClient client, CancellationToken cancellationToken) { using (var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) using (client) using (var server = ConnectToServer(client)) { await server.ConnectAsync(_server, _port).ConfigureAwait(false); var clientData = OnClientConnected(client, server); try { var clientPipe = new Pipe(); var fillClientPipe = PipeHelper.FillPipeAsync(client.Client, clientPipe.Writer, cts.Token); var readClientPipe = ReadFromClientAsync(clientData, clientPipe.Reader, cancellationToken); var serverPipe = new Pipe(); var fillServerPipe = PipeHelper.FillPipeAsync(server.Client, serverPipe.Writer, cts.Token); var readServerPipe = ReadFromServerAsync(clientData, serverPipe.Reader, cancellationToken); var t = await Task.WhenAny(fillClientPipe, readClientPipe, fillServerPipe, readServerPipe).ConfigureAwait(false); await t; } catch (Exception ex) { Console.WriteLine("HandleClient failed"); Console.WriteLine(ex); } finally { cts.Cancel(); OnClientDisconnected(clientData); } } }
public async Task RunAsync(CancellationToken cancellationToken) { var pipe = new Pipe(); var fillPipe = PipeHelper.FillPipeAsync(Socket, pipe.Writer, cancellationToken); var handshake = HandshakeAsync(pipe.Reader, cancellationToken); var t = await Task.WhenAny(fillPipe, handshake).ConfigureAwait(false); await t; var readPipe = ReadPipeAsync(pipe.Reader, cancellationToken); t = await Task.WhenAny(fillPipe, readPipe).ConfigureAwait(false); await t; }