Skip to content

Instantly share code, notes, and snippets.

@lucasteles
Created September 3, 2024 15:07
Show Gist options
  • Save lucasteles/dc433c97c9c77f3b074f74cfc92ff2af to your computer and use it in GitHub Desktop.
Save lucasteles/dc433c97c9c77f3b074f74cfc92ff2af to your computer and use it in GitHub Desktop.
Deferred execution sample
/// <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