Skip to content

Commit

Permalink
Merge pull request #315 from FoundatioFx/feature/disposable-action
Browse files Browse the repository at this point in the history
Added Async Disposable Action
  • Loading branch information
niemyjski authored Oct 2, 2024
2 parents 37599b9 + 0e200d6 commit b851839
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
32 changes: 32 additions & 0 deletions src/Foundatio/Utility/AsyncDisposableAction.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Foundatio.Utility;

/// <summary>
/// A class that will call an <see cref="Func{TResult}"/> when Disposed.
/// </summary>
public sealed class AsyncDisposableAction : IAsyncDisposable
{
private Func<Task> _exitTask;

/// <summary>
/// Initializes a new instance of the <see cref="DisposableAction"/> class.
/// </summary>
/// <param name="exitTask">The exit action.</param>
public AsyncDisposableAction(Func<Task> exitTask)
{
_exitTask = exitTask;
}

/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
async ValueTask IAsyncDisposable.DisposeAsync()
{
var exitAction = Interlocked.Exchange(ref _exitTask, null);
if (exitAction is not null)
await _exitTask().AnyContext();
}
}
11 changes: 4 additions & 7 deletions src/Foundatio/Utility/DisposableAction.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Threading;

namespace Foundatio.Utility;

Expand All @@ -7,8 +8,7 @@ namespace Foundatio.Utility;
/// </summary>
public sealed class DisposableAction : IDisposable
{
private readonly Action _exitAction;
private bool _disposed;
private Action _exitAction;

/// <summary>
/// Initializes a new instance of the <see cref="DisposableAction"/> class.
Expand All @@ -24,10 +24,7 @@ public DisposableAction(Action exitAction)
/// </summary>
void IDisposable.Dispose()
{
if (_disposed)
return;

_exitAction();
_disposed = true;
var exitAction = Interlocked.Exchange(ref _exitAction, null);
exitAction?.Invoke();
}
}

0 comments on commit b851839

Please sign in to comment.