@@ -109,24 +109,44 @@ public async Task Duplicate_Stop_Caller_Does_Not_Wait_For_Synchronous_Startup() |
109 | 109 | using var inner = new SynchronouslyBlockingStopHostedService(); |
110 | 110 | var wrapper = new FlowSuppressingHostedService(inner); |
111 | 111 |
|
112 | | - var first = Task.Run(() => wrapper.StopAsync(CancellationToken.None)); |
113 | | - inner.WaitUntilEntered(); |
| 112 | + // The inner stop blocks synchronously. Dedicated threads keep both callers |
| 113 | + // independent of thread-pool starvation under parallel CI load. |
| 114 | + var first = Task.Factory.StartNew( |
| 115 | + () => wrapper.StopAsync(CancellationToken.None), |
| 116 | + CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap(); |
| 117 | + Task? second = null; |
114 | 118 |
|
115 | 119 | using var cancellationTokenSource = new CancellationTokenSource(); |
116 | 120 | cancellationTokenSource.Cancel(); |
117 | 121 |
|
118 | 122 | try |
119 | 123 | { |
120 | | - var second = Task.Run(() => wrapper.StopAsync(cancellationTokenSource.Token)); |
121 | | - await Assert.That(async () => await second.WaitAsync(TimeSpan.FromSeconds(1))) |
| 124 | + inner.WaitUntilEntered(); |
| 125 | + second = Task.Factory.StartNew( |
| 126 | + () => wrapper.StopAsync(cancellationTokenSource.Token), |
| 127 | + CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap(); |
| 128 | + await Assert.That(async () => await second.WaitAsync(TimeSpan.FromSeconds(5))) |
122 | 129 | .Throws<OperationCanceledException>(); |
123 | 130 | } |
124 | 131 | finally |
125 | 132 | { |
126 | 133 | inner.Release(); |
| 134 | + // Drain callers before disposing the synchronization gates, even if |
| 135 | + // the assertion or startup handshake fails. |
| 136 | + await first; |
| 137 | + if (second is not null) |
| 138 | + { |
| 139 | + try |
| 140 | + { |
| 141 | + await second; |
| 142 | + } |
| 143 | + catch (OperationCanceledException) when (cancellationTokenSource.IsCancellationRequested) |
| 144 | + { |
| 145 | + // Cancellation is asserted above while the inner stop is blocked. |
| 146 | + } |
| 147 | + } |
127 | 148 | } |
128 | 149 |
|
129 | | - await first; |
130 | 150 | await Assert.That(inner.StopCalls).IsEqualTo(1); |
131 | 151 | } |
132 | 152 |
|
|