using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace IpClient.Core { public static class MyExtensions { public static async Task MyConnectAsync(this TcpClient tcpClient, string host, int port, CancellationToken cancellationToken) { if (tcpClient == null) { throw new ArgumentNullException(nameof(tcpClient)); } cancellationToken.ThrowIfCancellationRequested(); using (cancellationToken.Register(() => tcpClient.Close())) { try { cancellationToken.ThrowIfCancellationRequested(); await tcpClient.ConnectAsync(host, port).ConfigureAwait(false); } catch (NullReferenceException) when (cancellationToken.IsCancellationRequested) { cancellationToken.ThrowIfCancellationRequested(); } catch (ObjectDisposedException eDisposedException) { Trace.WriteLine("Caught: {0}", eDisposedException.Message); } } } } }