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
TInThe input type supplied to predicates and handlers.
TOutThe 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()
Creates a new AsyncStrategy<TIn, TOut>.Builder for configuring an AsyncStrategy<TIn, TOut>.
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
inputTInThe input value passed to predicates and handlers.
ctCancellationTokenAn 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.