public async Task Run(CancellationToken ct) { const string funcName = nameof(Run); Log.InfoEx(funcName, $"[{_logName}] Start client connection to host {_hostIp}:{_hostPort}", false); // Register CancellationToken to call _tcpClient.Close() on cancel. // ConnectAsync() then throws ObjectDisposedException and cancels properly. using (ct.Register(() => _tcpClient?.Close())) { await MainTask(ct).ContinueWith(t => Log.DebugEx(funcName, $"[{_logName}] Stop client connection to host {_hostIp}:{_hostPort}"), CancellationToken.None); } }
public async Task Run(CancellationToken ct) { const string funcName = nameof(Run); _tcpListener.Start(); Log.InfoEx(funcName, $"[{_logName}] Start listening to port {_port}"); // Register CancellationToken to call _tcpListener.Stop() on cancel. // AcceptTcpClientAsync() then throws SocketException and cancels properly. using (ct.Register(() => _tcpListener.Stop())) { await MainTask(ct).ContinueWith(t => Log.DebugEx(funcName, $"[{_logName}] Stop listening to port {_port}"), CancellationToken.None); } }