-
-
Notifications
You must be signed in to change notification settings - Fork 244
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #315 from FoundatioFx/feature/disposable-action
Added Async Disposable Action
- Loading branch information
Showing
2 changed files
with
36 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters