public void SendAndReceive() { try { var sendThread = new Thread(() => { SendLoop.Loop(sendQueue, stream, cancellationTokenSource.Token); }) { IsBackground = true }; sendThread.Start(); while (true) { MemoryStream message = Parser.ReadOneMessage(stream); receiveQueue.Writer.TryWrite(message); } } catch (EndOfStreamException) { receiveQueue.Writer.TryComplete(); } finally { cancellationTokenSource.Cancel(); stream?.Close(); client?.Close(); } }
void ConnectAndReceiveLoop(Uri uri) { // connect and handshake try { Connect(uri); connectCompletionSource.TrySetResult(); var sendThread = new Thread(() => { SendLoop.Loop(sendQueue, stream, cancellationTokenSource.Token); }) { IsBackground = true }; sendThread.Start(); while (true) { MemoryStream message = Parser.ReadOneMessage(stream); receiveQueue.Writer.TryWrite(message); } } catch (EndOfStreamException) { connectCompletionSource.TrySetResult(); receiveQueue.Writer.TryComplete(); } catch (Exception e) { connectCompletionSource.TrySetException(e); } finally { cancellationTokenSource.Cancel(); stream?.Close(); client?.Close(); } }