|
| 1 | +using System.Runtime.CompilerServices; |
1 | 2 | using Polly.CircuitBreaker; |
2 | 3 |
|
3 | 4 | namespace Polly.Core.Tests.CircuitBreaker.Controller; |
@@ -167,4 +168,38 @@ public async Task Dispose_EnsureNoBackgroundProcessing() |
167 | 168 |
|
168 | 169 | scheduler.ProcessingTask.IsCompleted.ShouldBeTrue(); |
169 | 170 | } |
| 171 | + |
| 172 | + [Fact] |
| 173 | + public void Constructor_DoesNotCaptureAmbientExecutionContext() |
| 174 | + { |
| 175 | + // The background processing loop outlives the code that creates the executor, |
| 176 | + // so it must not capture (and keep alive) the ambient ExecutionContext. |
| 177 | + var (executor, reference) = CreateExecutorWithAmbientValue(); |
| 178 | + |
| 179 | + for (var i = 0; i < 3; i++) |
| 180 | + { |
| 181 | + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true); |
| 182 | + GC.WaitForPendingFinalizers(); |
| 183 | + } |
| 184 | + |
| 185 | + // Keep the executor (and its background processing task) alive for the check: |
| 186 | + // without the fix, the task's captured ExecutionContext keeps the ambient value alive. |
| 187 | + GC.KeepAlive(executor); |
| 188 | + reference.IsAlive.ShouldBeFalse(); |
| 189 | + |
| 190 | + executor.Dispose(); |
| 191 | + } |
| 192 | + |
| 193 | + [MethodImpl(MethodImplOptions.NoInlining)] |
| 194 | + private static (ScheduledTaskExecutor Executor, WeakReference Reference) CreateExecutorWithAmbientValue() |
| 195 | + { |
| 196 | + var asyncLocal = new AsyncLocal<object?>(); |
| 197 | + var value = new object(); |
| 198 | + asyncLocal.Value = value; |
| 199 | + |
| 200 | + var executor = new ScheduledTaskExecutor(); |
| 201 | + |
| 202 | + asyncLocal.Value = null; |
| 203 | + return (executor, new WeakReference(value)); |
| 204 | + } |
170 | 205 | } |
0 commit comments