|
| 1 | +# AsyncTemplate<TContext, TResult> |
| 2 | + |
| 3 | +A fluent, allocation-light async Template: define a fixed workflow (before → step → after), add async/sync hooks, opt into synchronization, and choose throwing or non-throwing execution. |
| 4 | + |
| 5 | +--- |
| 6 | + |
| 7 | +## What it is |
| 8 | + |
| 9 | +- Async skeleton with three phases: Before (0..n), Step (1), After (0..n) |
| 10 | +- Non-throwing path via `TryExecuteAsync(context)` returning `(ok, result, error)` |
| 11 | +- Optional per-instance synchronization via `SemaphoreSlim` |
| 12 | +- Immutable and thread-safe after `Build()` |
| 13 | + |
| 14 | +--- |
| 15 | + |
| 16 | +## TL;DR |
| 17 | + |
| 18 | +```csharp |
| 19 | +using PatternKit.Behavioral.Template; |
| 20 | + |
| 21 | +var tpl = AsyncTemplate<int, string> |
| 22 | + .Create(async (id, ct) => |
| 23 | + { |
| 24 | + await Task.Delay(15, ct); |
| 25 | + if (id < 0) throw new InvalidOperationException("invalid id"); |
| 26 | + return $"VAL-{id}"; |
| 27 | + }) |
| 28 | + .Before((id, ct) => { Console.WriteLine($"[BeforeAsync] {id}"); return default; }) |
| 29 | + .After((id, res, ct) => { Console.WriteLine($"[AfterAsync] {id} -> {res}"); return default; }) |
| 30 | + .OnError((id, err, ct) => { Console.WriteLine($"[ErrorAsync] {id}: {err}"); return default; }) |
| 31 | + .Synchronized() // optional |
| 32 | + .Build(); |
| 33 | + |
| 34 | +var (ok, result, error) = await tpl.TryExecuteAsync(42); |
| 35 | +Console.WriteLine(ok ? $"OK: {result}" : $"ERR: {error}"); |
| 36 | +``` |
| 37 | + |
| 38 | +--- |
| 39 | + |
| 40 | +## API shape |
| 41 | + |
| 42 | +```csharp |
| 43 | +var tpl = AsyncTemplate<TContext, TResult> |
| 44 | + .Create(static (TContext ctx, CancellationToken ct) => /* ValueTask<TResult> */) |
| 45 | + .Before(static (TContext ctx, CancellationToken ct) => /* ValueTask */) // 0..n (async) |
| 46 | + .Before(static (TContext ctx) => { /* side-effect */ }) // 0..n (sync overload) |
| 47 | + .After(static (TContext ctx, TResult res, CancellationToken ct) => /* ValueTask */) // 0..n (async) |
| 48 | + .After(static (TContext ctx, TResult res) => { /* side-effect */ }) // 0..n (sync overload) |
| 49 | + .OnError(static (TContext ctx, string error, CancellationToken ct) => /* ValueTask */) // 0..n (async) |
| 50 | + .OnError(static (TContext ctx, string error) => { /* observe */ }) // 0..n (sync overload) |
| 51 | + .Synchronized() // optional |
| 52 | + .Build(); |
| 53 | + |
| 54 | +// Throws on failure |
| 55 | +TResult result = await tpl.ExecuteAsync(context, ct); |
| 56 | + |
| 57 | +// Non-throwing; returns tuple (ok, result?, error?) |
| 58 | +(bool ok, TResult? result, string? error) = await tpl.TryExecuteAsync(context, ct); |
| 59 | +``` |
| 60 | + |
| 61 | +Notes |
| 62 | +- Multiple hooks compose; registration order is invocation order. |
| 63 | +- OnError hooks run only when TryExecuteAsync catches an exception. |
| 64 | +- Synchronized() uses an async mutex; keep the critical section small. |
| 65 | + |
| 66 | +--- |
| 67 | + |
| 68 | +## Testing (TinyBDD-style) |
| 69 | + |
| 70 | +```csharp |
| 71 | +using PatternKit.Behavioral.Template; |
| 72 | +using TinyBDD; |
| 73 | +using TinyBDD.Xunit; |
| 74 | + |
| 75 | +var tpl = AsyncTemplate<string, int> |
| 76 | + .Create(async (ctx, ct) => { await Task.Yield(); return ctx.Length; }) |
| 77 | + .Before((ctx, ct) => { Console.WriteLine($"before:{ctx}"); return default; }) |
| 78 | + .After((ctx, res, ct) => { Console.WriteLine($"after:{ctx}:{res}"); return default; }) |
| 79 | + .Build(); |
| 80 | + |
| 81 | +var r = await tpl.ExecuteAsync("abc"); // 3 |
| 82 | +``` |
| 83 | + |
| 84 | +--- |
| 85 | + |
| 86 | +## Design notes |
| 87 | + |
| 88 | +- No reflection/LINQ in the hot path; simple async delegate calls and an optional async lock. |
| 89 | +- Immutable after Build() so instances can be safely shared across threads. |
| 90 | +- Sync and async hooks both supported; they are adapted internally to async. |
| 91 | + |
| 92 | +--- |
| 93 | + |
| 94 | +## Gotchas |
| 95 | + |
| 96 | +- ExecuteAsync throws; OnError hooks are not invoked by ExecuteAsync. |
| 97 | +- TryExecuteAsync captures ex.Message as error; result is default when failing. |
| 98 | +- Synchronized serializes executions; prefer idempotent, short steps. |
| 99 | + |
| 100 | +--- |
| 101 | + |
| 102 | +## See also |
| 103 | + |
| 104 | +- Subclassing: [TemplateMethod<TContext, TResult>](./templatemethod.md) |
| 105 | +- Synchronous fluent: [Template<TContext, TResult>](./template.md) |
| 106 | +- Demos: [Template Method Demo](../../../examples/template-method-demo.md), [Template Method Async Demo](../../../examples/template-method-async-demo.md) |
0 commit comments