Table of Contents

Class AsyncActionStrategy<TIn>

Namespace
PatternKit.Behavioral.Strategy
Assembly
PatternKit.Core.dll

Composable, asynchronous action strategy that selects the first matching branch (predicate + handler) and executes its handler for side effects.

public sealed class AsyncActionStrategy<TIn>

Type Parameters

TIn

The input type supplied to predicates and handlers.

Inheritance
AsyncActionStrategy<TIn>
Inherited Members

Examples

Basic usage:

var logs = new List<string>();
var strat = AsyncActionStrategy<int>.Create()
    .When((n, ct) => new ValueTask<bool>(n < 0))
        .Then(async (n, ct) => { await Task.Delay(10, ct); logs.Add("negative"); })
    .When((n, ct) => new ValueTask<bool>(n == 0))
        .Then((n, ct) => { logs.Add("zero"); return default; })
    .Default((n, ct) => { logs.Add("positive"); return default; })
    .Build();

await strat.ExecuteAsync(5, CancellationToken.None); // logs "positive"

Remarks

This strategy evaluates predicates in the order they were added. The first predicate that returns true determines the chosen handler. If no predicates match, an optional Default(Handler) handler is invoked. Without a default, ExecuteAsync(TIn, CancellationToken) throws to signal that no branch matched.

Instances built via Build() are immutable and thread-safe for concurrent execution, assuming supplied predicates/handlers are thread-safe.

Methods

Create()

public static AsyncActionStrategy<TIn>.Builder Create()

Returns

AsyncActionStrategy<TIn>.Builder

A new AsyncActionStrategy<TIn>.Builder instance.

ExecuteAsync(TIn, CancellationToken)

Executes the strategy by evaluating predicates in order and invoking the first matching handler.

public ValueTask ExecuteAsync(TIn input, CancellationToken ct = default)

Parameters

input TIn

The input value passed to predicates and handlers.

ct CancellationToken

An optional cancellation token.

Returns

ValueTask

A ValueTask that completes when the chosen handler finishes.

Remarks

If no predicates match and a default handler was configured, the default handler is invoked. Otherwise the method throws to indicate that no branch matched.

Exceptions

InvalidOperationException

Thrown when no predicate matches and no default handler is configured.

TryExecuteAsync(TIn, CancellationToken)

Tries to execute the strategy. Returns true if a handler was executed.

public ValueTask<bool> TryExecuteAsync(TIn input, CancellationToken ct = default)

Parameters

input TIn

The input value passed to predicates and handlers.

ct CancellationToken

An optional cancellation token.

Returns

ValueTask<bool>

true if a predicate matched and its handler was executed; otherwise false.

See Also