Table of Contents

Class AsyncStrategy<TIn, TOut>

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

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

public sealed class AsyncStrategy<TIn, TOut>

Type Parameters

TIn

The input type supplied to predicates and handlers.

TOut

The result type returned by handlers.

Inheritance
AsyncStrategy<TIn, TOut>
Inherited Members
Extension Methods

Examples

Basic usage:

var strat = AsyncStrategy<int, string>.Create()
    .When((n, ct) => new ValueTask<bool>(n < 0))
        .Then((n, ct) => new ValueTask<string>("negative"))
    .When((n, ct) => new ValueTask<bool>(n == 0))
        .Then((n, ct) => new ValueTask<string>("zero"))
    .Default((n, ct) => new ValueTask<string>("positive"))
    .Build();

var result = await strat.ExecuteAsync(5, CancellationToken.None); // "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 AsyncStrategy<TIn, TOut>.Builder Create()

Returns

AsyncStrategy<TIn, TOut>.Builder

A new AsyncStrategy<TIn, TOut>.Builder instance.

ExecuteAsync(TIn, CancellationToken)

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

public ValueTask<TOut> 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<TOut>

A ValueTask<TResult> that completes with the result of the chosen handler.

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.

See Also

AsyncStrategy<TIn, TOut>.Builder