From d2ed00a046c2d47374ee7a1517fabf2c4eb80c81 Mon Sep 17 00:00:00 2001 From: Travis Illig Date: Wed, 9 Oct 2024 08:48:29 -0700 Subject: [PATCH] Make async disposal test more deterministic. --- test/Autofac.Test/Core/DisposerTests.cs | 5 ++- test/Autofac.Test/Util/AsyncDisposeTracker.cs | 32 ++++++++++++++++--- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/test/Autofac.Test/Core/DisposerTests.cs b/test/Autofac.Test/Core/DisposerTests.cs index 04847edff..7d9d3ade7 100644 --- a/test/Autofac.Test/Core/DisposerTests.cs +++ b/test/Autofac.Test/Core/DisposerTests.cs @@ -61,7 +61,9 @@ public void CannotAddObjectsToDisposerAfterSyncDispose() [Fact] public async Task DisposerDisposesOfObjectsAsyncIfIAsyncDisposableDeclared() { - var instance = new AsyncDisposeTracker(); + var semaphore = new SemaphoreSlim(1); + var instance = new AsyncDisposeTracker(semaphore); + await semaphore.WaitAsync(); var disposer = new Disposer(); disposer.AddInstanceForDisposal(instance); @@ -74,6 +76,7 @@ public async Task DisposerDisposesOfObjectsAsyncIfIAsyncDisposableDeclared() Assert.False(instance.IsAsyncDisposed); // Now we wait. + semaphore.Release(); await result; Assert.False(instance.IsSyncDisposed); diff --git a/test/Autofac.Test/Util/AsyncDisposeTracker.cs b/test/Autofac.Test/Util/AsyncDisposeTracker.cs index 70e81d94a..8defe1562 100644 --- a/test/Autofac.Test/Util/AsyncDisposeTracker.cs +++ b/test/Autofac.Test/Util/AsyncDisposeTracker.cs @@ -5,12 +5,24 @@ namespace Autofac.Test.Util; public sealed class AsyncDisposeTracker : IDisposable, IAsyncDisposable { + private readonly SemaphoreSlim _semaphore; + public event EventHandler Disposing; public bool IsSyncDisposed { get; set; } public bool IsAsyncDisposed { get; set; } + public AsyncDisposeTracker() + : this(null) + { + } + + public AsyncDisposeTracker(SemaphoreSlim semaphore) + { + _semaphore = semaphore; + } + public void Dispose() { IsSyncDisposed = true; @@ -20,10 +32,20 @@ public void Dispose() public async ValueTask DisposeAsync() { - await Task.Delay(1); - - IsAsyncDisposed = true; - - Disposing?.Invoke(this, EventArgs.Empty); + if (_semaphore != null) + { + await _semaphore.WaitAsync(); + } + + try + { + IsAsyncDisposed = true; + + Disposing?.Invoke(this, EventArgs.Empty); + } + finally + { + _semaphore?.Release(); + } } }