diff --git a/tests/Cosmos.Network.Http.Tests/HttpLoopbackTests.cs b/tests/Cosmos.Network.Http.Tests/HttpLoopbackTests.cs index 665f558..c0ccfdf 100644 --- a/tests/Cosmos.Network.Http.Tests/HttpLoopbackTests.cs +++ b/tests/Cosmos.Network.Http.Tests/HttpLoopbackTests.cs @@ -28,6 +28,7 @@ private sealed class TestServer : IDisposable private readonly List _errors = new List(); private int _taken; private int _handled; + private volatile bool _restarting; internal TestServer(bool https = false, SslProtocols protocols = SslProtocols.Tls12) { @@ -55,6 +56,22 @@ internal TestServer(bool https = false, SslProtocols protocols = SslProtocols.Tl internal void Start() => _listener.Start(); + // Stop then Start with the serving thread held back: seeing the Stop between the two, it would return from + // GetContext, close the listener and leave Start to throw. + internal void Restart() + { + _restarting = true; + try + { + _listener.Stop(); + _listener.Start(); + } + finally + { + _restarting = false; + } + } + private void Serve() { while (_listener.IsListening) @@ -62,6 +79,12 @@ private void Serve() HttpListenerContext context = _listener.GetContext(); if (context == null) { + if (_restarting) + { + SpinWait.SpinUntil(() => !_restarting); + continue; + } + break; } @@ -818,8 +841,7 @@ public void Listener_StopThenStart_KeepsServing() Assert.AreEqual("Hello, Cosmos", client.GetString(server.Url("/hello"))); // From this thread, before the serving one acts on the Stop: undone. - server.Stop(); - server.Start(); + server.Restart(); Thread.Sleep(200); Assert.AreEqual("Hello, Cosmos", client.GetString(server.Url("/hello")));