From f07e3e7e9d86c976c827086ec14d9f883c1f436e Mon Sep 17 00:00:00 2001 From: valentinbreiz Date: Thu, 8 Oct 2026 11:14:00 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Hold=20the=20test=20server's=20t?= =?UTF-8?q?hread=20back=20across=20a=20Stop=20then=20Start?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Seeing the Stop between the two, it returned from GetContext and closed the listener, and Start threw ObjectDisposedException. --- .../HttpLoopbackTests.cs | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) 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")));