Skip to content

Commit

Permalink
Make async disposal test more deterministic.
Browse files Browse the repository at this point in the history
  • Loading branch information
tillig committed Oct 9, 2024
1 parent edb63ea commit d2ed00a
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
5 changes: 4 additions & 1 deletion test/Autofac.Test/Core/DisposerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -74,6 +76,7 @@ public async Task DisposerDisposesOfObjectsAsyncIfIAsyncDisposableDeclared()
Assert.False(instance.IsAsyncDisposed);

// Now we wait.
semaphore.Release();
await result;

Assert.False(instance.IsSyncDisposed);
Expand Down
32 changes: 27 additions & 5 deletions test/Autofac.Test/Util/AsyncDisposeTracker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,24 @@ namespace Autofac.Test.Util;

public sealed class AsyncDisposeTracker : IDisposable, IAsyncDisposable
{
private readonly SemaphoreSlim _semaphore;

public event EventHandler<EventArgs> 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;
Expand All @@ -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();
}
}
}

0 comments on commit d2ed00a

Please sign in to comment.