@@ -13,7 +13,7 @@ public class TestHttpServer : IDisposable
1313 private readonly CancellationTokenSource _cts = new ( ) ;
1414 private readonly Func < HttpListenerContext , Task > _handler ;
1515 private readonly HttpListener _listener ;
16- private readonly Thread _listenerThread ;
16+ private readonly Task _listenerTask ;
1717
1818 public string BaseUrl { get ; private set ; }
1919
@@ -60,12 +60,7 @@ public TestHttpServer(Func<HttpListenerContext, Task> handler)
6060 throw new InvalidOperationException ( "Could not find a free port to listen on" ) ;
6161 BaseUrl = $ "http://localhost:{ port } ";
6262
63- _listenerThread = new Thread ( ( ) =>
64- {
65- RequestLoop ( ) . GetAwaiter ( ) . GetResult ( ) ;
66- } ) ;
67-
68- _listenerThread . Start ( ) ;
63+ _listenerTask = RequestLoop ( ) ;
6964 }
7065
7166 public void Dispose ( )
@@ -74,15 +69,11 @@ public void Dispose()
7469 _listener . Stop ( ) ;
7570 try
7671 {
77- _listenerThread . Join ( ) ;
78- }
79- catch ( ThreadStateException )
80- {
81- // Ignore if the listener thread is already dead
72+ _listenerTask . GetAwaiter ( ) . GetResult ( ) ;
8273 }
83- catch ( ThreadInterruptedException )
74+ catch ( TaskCanceledException )
8475 {
85- // Ignore interrupted listener thread, it's now closed anyway
76+ // Ignore
8677 }
8778 GC . SuppressFinalize ( this ) ;
8879 }
@@ -106,11 +97,6 @@ private async Task RequestLoop()
10697 // it's stopped
10798 break ;
10899 }
109- catch ( TaskCanceledException )
110- {
111- // Ignore, the CTS was cancelled
112- break ;
113- }
114100 }
115101
116102 private async Task HandleRequest ( HttpListenerContext context )
0 commit comments