Created
September 3, 2024 15:07
-
-
Save lucasteles/dc433c97c9c77f3b074f74cfc92ff2af to your computer and use it in GitHub Desktop.
Deferred execution sample
This file contains hidden or 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
/// <summary> | |
/// Disposable static functions | |
/// </summary> | |
public static class Disposable | |
{ | |
/// <inheritdoc /> | |
/// <summary> | |
/// Create new deferred context | |
/// </summary> | |
public readonly struct Deferred(Action action) : IDisposable | |
{ | |
/// <inheritdoc /> | |
public void Dispose() => action?.Invoke(); | |
} | |
/// <inheritdoc /> | |
/// <summary> | |
/// Create new deferred context | |
/// </summary> | |
public readonly struct DeferredValueTask(Func<ValueTask> action) : IAsyncDisposable | |
{ | |
/// <inheritdoc /> | |
public async ValueTask DisposeAsync() | |
{ | |
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract | |
if (action is not null) | |
await action(); | |
} | |
} | |
/// <inheritdoc /> | |
/// <summary> | |
/// Create new deferred context | |
/// </summary> | |
public readonly struct DeferredTask(Func<Task> action) : IAsyncDisposable | |
{ | |
/// <inheritdoc /> | |
public async ValueTask DisposeAsync() | |
{ | |
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract | |
if (action is not null) | |
await action(); | |
} | |
} | |
/// <summary> | |
/// Defer action execution with Dispose | |
/// </summary> | |
public static Deferred Defer(Action action) => new(action); | |
/// <summary> | |
/// Defer async action execution with DisposeAsync | |
/// </summary> | |
public static DeferredValueTask Defer(Func<ValueTask> action) => new(action); | |
/// <summary> | |
/// Defer async action execution with DisposeAsync | |
/// </summary> | |
public static DeferredTask Defer(Func<Task> action) => new(action); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment