diff --git a/SharpXMPP.NUnit/Compat/TcpClientExTests.cs b/SharpXMPP.NUnit/Compat/TcpClientExTests.cs index b2b24f3..47d42b5 100644 --- a/SharpXMPP.NUnit/Compat/TcpClientExTests.cs +++ b/SharpXMPP.NUnit/Compat/TcpClientExTests.cs @@ -10,13 +10,14 @@ namespace SharpXMPP.Compat { public class TcpClientExTests { - private static int GetFreePort() + private static IPEndPoint GetFreePortEndpoint() { - var host = new TcpListener(new IPEndPoint(IPAddress.Loopback, 0)); + var endpoint = new IPEndPoint(IPAddress.Loopback, 0); + var host = new TcpListener(endpoint); host.Start(); try { - return ((IPEndPoint)host.LocalEndpoint).Port; + return (IPEndPoint)host.LocalEndpoint; } finally { @@ -39,42 +40,27 @@ public void TestCancellation() int cancelled = 0; // Connecting to a free port takes enough time for the tasks to be cancelled in time. - var port = GetFreePort(); - TcpListener host = null; - if (Environment.OSVersion.Platform == PlatformID.Unix) + var endpoint = GetFreePortEndpoint(); + for (int i = 0; i < iterations; ++i) { - // Since the port trick doesn't work on Linux, do this. - host = new TcpListener(new IPEndPoint(IPAddress.Loopback, port)); - host.Start(); - } - - try - { - for (int i = 0; i < iterations; ++i) + Task.Run(async () => { - Task.Run(async () => - { - using var cts = new CancellationTokenSource(); - var token = cts.Token; + using var cts = new CancellationTokenSource(); + var token = cts.Token; - using var client = new TcpClient(); - var task = client.ConnectWithCancellationAsync(IPAddress.Loopback, port, token); - cts.Cancel(); + using var client = new TcpClient(); + var task = client.ConnectWithCancellationAsync(endpoint.Address, endpoint.Port, token); + cts.Cancel(); - try - { - await task; - } - catch (OperationCanceledException) - { - ++cancelled; - } - }).Wait(); - } - } - finally - { - host?.Stop(); + try + { + await task; + } + catch (OperationCanceledException) + { + ++cancelled; + } + }).Wait(); } Assert.Greater(cancelled, 0);