Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Async Disposable Action #315

Merged
merged 1 commit into from
Oct 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why add the locking here? I've never seen any dispose methods have locking in them. I'm pretty sure the .NET runtime isn't going to call dispose a bunch of times. I suppose you could call it manually a bunch of times in a row, but it still seems like overhead to add locking here.

exitAction?.Invoke();
}
}