Durable task recipes
These compiled examples use grains which derive from
DurableGrain and the contracts from
Durable tasks. Configure Journaling,
Durable Jobs, and the durable task runtime as shown in
Configure the silo and clients.
Each recipe’s outcome is observable by polling the task
and through the runtime transitions
which DurableTaskEvents reports.
Fan out to every line with a named WhenAll
Section titled “Fan out to every line with a named WhenAll”Task: reserve stock for every order line concurrently, and continue with each line’s result in line order.
bool[] reserved;try{ await DurableTask.Delay(TimeSpan.FromMinutes(1)).WithId("grace-period"); DurableTask.RunInline("validate", () => SetStatus(OrderStatus.AwaitingValidation));
// Reserves every line concurrently, as the children reserve/0, reserve/1, and so on. reserved = await order.Lines.Select(line => Catalog(line.ProductId).ReserveAsync(OrderId, line.Units)) .WhenAll() .WithId("reserve");}catch (OperationCanceledException) when (DurableTask.Current.IsTaskCancellationRequested){ // WhenAll has waited for every reservation, so none is still running. return await CancelOrderAsync(order.Lines, DurableTask.Current.TaskCancellationReason);}
if (Array.IndexOf(reserved, false) >= 0){ return await CancelOrderAsync(order.Lines, "A line is out of stock.");}DurableTask.WhenAll schedules
one reservation per line in one batch, which the order grain commits with one journal
write, and returns a bool[] in input order. It waits for every reservation, including
after a cancellation request, so the catch block runs when no reservation is still
running. WithId("reserve") identifies the inputs as reserve/0, reserve/1, and so
on.
Pitfalls:
- Build the inputs in a deterministic order, such as the order’s line order. The input index is part of each input’s task ID.
- Name the combinator. An unnamed combinator’s generated ID counts the combinators which ran before it, so adding one earlier in a later deployment renumbers its inputs.
WhenAllthrows the first failure in input order, then the first cancellation. To act on each input’s own outcome, useWhenAllCompleted.
Verify: the order grain lists place-order-{orderId}/reserve/0 through
reserve/{n-1}, each Completed with its True or False result, and each catalog
grain lists a task with the same ID.
Take the first result and cancel the rest with Race
Section titled “Take the first result and cancel the rest with Race”Task: take the first shipping quote from two carriers, and cancel the other carrier’s request.
[GenerateSerializer, Immutable]public sealed record ShippingQuote(string Carrier, decimal Price);
public interface ICarrierGrain : IGrainWithStringKey{ // Returns null when the carrier doesn't serve the route. DurableTask<ShippingQuote?> QuoteAsync(string route);}
public interface IShippingGrain : IGrainWithGuidKey{ DurableTask<ShippingQuote?> QuoteFirstAsync(string route);
DurableTask<ShippingQuote?> QuoteGroundAsync(string route);
DurableTask<ShippingQuote[]> CollectQuotesAsync(string route, string[] carriers, int count);}
public sealed partial class ShippingGrain : DurableGrain, IShippingGrain{ // Returns the first carrier's quote once the other carrier's request has settled. public async DurableTask<ShippingQuote?> QuoteFirstAsync(string route) { var (_, quote) = await DurableTask.Race([Carrier("ground").QuoteAsync(route), Carrier("air").QuoteAsync(route)]) .WithId("first-quote"); return quote; }
private ICarrierGrain Carrier(string name) => GrainFactory.GetGrain<ICarrierGrain>(name);}DurableTask.Race schedules the
requests as first-quote/0 and first-quote/1 and selects the one which completed
first. The grain stamps each input’s result with a durable completion sequence, so a
replay selects the same winner even when the other request has completed since. Race
then requests cancellation of the other request with the reason
Another task won the race. and waits until that request is terminal, so the workflow
continues only after both carrier calls have settled. Race<TResult> returns the
winner’s index and result.
Pitfalls:
- A winner which failed or was canceled fails
Race. Return a value, such asnull, from inputs whose failure is an expected outcome. - Cancellation is cooperative. A carrier which ignores the request keeps the race waiting until its call completes, and the race discards that call’s result.
- To leave the other inputs running, use DurableTask.WhenAny, whose other inputs run until they complete or the runtime deletes the task’s execution tree.
Verify: while the slower request settles, the shipping grain lists it as
Canceling with the reason Another task won the race.; once QuoteFirstAsync
returns, first-quote/0 and first-quote/1 are both terminal.
Time out a call with WaitAsync
Section titled “Time out a call with WaitAsync”Task: request a quote from the ground carrier, and give up after two minutes.
public async DurableTask<ShippingQuote?> QuoteGroundAsync(string route){ try { return await Carrier("ground").QuoteAsync(route).WaitAsync(TimeSpan.FromMinutes(2)).WithId("ground-quote"); } catch (TimeoutException) { // The carrier's request ended canceled after the timeout requested its cancellation. return null; }}DurableTaskExtensions.WaitAsync
races the call, ground-quote/0, with a durable delay, ground-quote/1. The runtime
records the delay’s due time, so a replay after a deactivation keeps the original
deadline: the timeout counts from the first run. When the delay elapses first, the call
receives a cancellation request with the reason
The operation timed out after 00:02:00., and WaitAsync waits for the carrier’s
outcome. A call which ends canceled throws TimeoutException, whose inner
exception is the call’s OperationCanceledException; a quote which the carrier returns
anyway is the result. When the call completes first, WaitAsync cancels the delay and
returns the call’s result or throws its failure.
WaitUntilAsync takes an absolute
deadline instead.
Pitfalls:
- Compute absolute deadlines from DurableTaskContext.UtcNow, so a replay computes the same deadline.
- Catch
TimeoutExceptionto handle the timeout. AnOperationCanceledExceptionreports another cancellation, such as the workflow’s own. Race(...).WaitAsync(timeout).WithId(name)bounds a whole race, which then runs as the child{name}/0with its inputs beneath it.- For a task which is already scheduled, ScheduledTask.WaitAsync with a timeout applies the same rules. Outside a durable task, such as in a client, it measures the timeout on the system clock.
Verify: the shipping grain lists ground-quote/1 as Delayed until its due time.
After a timeout, ground-quote/0 reports the reason
The operation timed out after 00:02:00., and the workflow returns null once the
carrier’s request ends canceled.
Compensate inline when the workflow is canceled
Section titled “Compensate inline when the workflow is canceled”Task: when the buyer cancels the order during validation, release every reservation and record why the order was canceled.
The catch block in the fan-out recipe
filters on IsTaskCancellationRequested, so it handles the workflow’s own task
cancellation, and passes
DurableTaskContext.TaskCancellationReason
to the compensation:
private async Task<OrderResult> CancelOrderAsync(OrderLine[] lines, string? reason){ // The release is shielded, so it runs to completion after the cancellation which ended the workflow. await lines.Select(line => Catalog(line.ProductId).ReleaseAsync(OrderId)) .WhenAll() .WithId("release") .Shielded(); DurableTask.RunInline("cancel", () => SetStatus(OrderStatus.Cancelled)); return new OrderResult(OrderStatus.Cancelled, reason);}Children which a canceled task starts terminate as canceled without running, unless the
task starts them with
Shielded. The shielded release
combinator shields each of its inputs, so the inputs and the cancel effect run to
completion, and the
workflow returns an OrderResult which records the reason. A reservation which never
ran leaves nothing to release, so ReleaseAsync returns whether the order held a
reservation, and releasing every line is safe:
public sealed class CatalogItemGrain : DurableGrain, ICatalogItemGrain{ private readonly IDurableValue<int> _available; private readonly IDurableDictionary<Guid, int> _reservations;
public CatalogItemGrain() { _available = StateManager.GetOrAddValue<int>("available"); _reservations = StateManager.GetOrAddDictionary<Guid, int>("reservations"); }
public async Task RestockAsync(int units) { _available.Value += units; await WriteStateAsync(); }
// The state change and the task's result commit in one journal write. public async DurableTask<bool> ReserveAsync(Guid orderId, int units) { if (units <= 0 || _available.Value < units) { return false; }
_available.Value -= units; _reservations[orderId] = units; return true; }
public async DurableTask<bool> ReleaseAsync(Guid orderId) { if (!_reservations.Remove(orderId, out var units)) { return false; }
_available.Value += units; return true; }}Pitfalls:
- Shield every compensating child. A child which isn’t shielded terminates as canceled without running.
- Make compensations idempotent and report whether they acted, so the workflow can compensate without knowing which steps ran.
- An abort runs no compensation. Abort is for tasks whose compensation is stuck.
- Work which must outlive the workflow, such as cleanup after the workflow’s result is delivered, belongs in a detached task.
Verify: after CancelAsync during the grace period, the order grain lists
grace-period as Canceled, release/{n} and cancel as Completed, and the root
task as Completed with an OrderResult whose description is Cancelled by the buyer..
Settle every input and inspect each outcome
Section titled “Settle every input and inspect each outcome”Task: reserve every line, and when any reservation fails, is rejected, or is canceled, release exactly the lines whose reservation succeeded.
public interface IAllocationGrain : IGrainWithGuidKey{ DurableTask<bool> AllocateAsync(OrderLine[] lines);}
public sealed class AllocationGrain : DurableGrain, IAllocationGrain{ private Guid OrderId => this.GetPrimaryKey();
public async DurableTask<bool> AllocateAsync(OrderLine[] lines) { var reservations = await lines.Select(line => Catalog(line.ProductId).ReserveAsync(OrderId, line.Units)) .WhenAllCompleted() .WithId("reserve"); if (reservations.All(reservation => reservation.TryGetResult(out var reserved) && reserved)) { return true; }
// Releases exactly the lines whose reservation succeeded, including after a cancellation request. var held = lines.Where((_, i) => reservations[i].TryGetResult(out var reserved) && reserved); await held.Select(line => Catalog(line.ProductId).ReleaseAsync(OrderId)) .WhenAll() .WithId("release") .Shielded();
DurableTask.Current.CancellationToken.ThrowIfCancellationRequested(); return false; }
private ICatalogItemGrain Catalog(int productId) => GrainFactory.GetGrain<ICatalogItemGrain>(productId);}DurableTask.WhenAllCompleted
schedules every input, waits until each is terminal, and returns their handles in input
order. An input’s failure or cancellation leaves the combinator successful, including
after the workflow’s own cancellation request, which reaches the inputs. Each handle has
observed its outcome, so
TryGetResult returns true with the result
of a reservation which completed successfully, and
Status,
Exception, and
GetResult inspect the others. The workflow
releases the held lines with a shielded combinator, so the release also runs when the
workflow was canceled, then rethrows the cancellation so the task ends as canceled.
Pitfalls:
- Branch on each handle’s outcome, not on the combined result: the combinator never throws for an input.
- Shield the release whenever the workflow can be canceled while it compensates.
WhenAllCompletedruns only when awaited inside a durable execution. For handles whichScheduleAllreturned earlier, ScheduledTask.WhenAllCompleted waits the same way.
Verify: with one line out of stock, the allocation grain lists reserve/{i} with
True and False results, a release/{n} input for each True line only, and the
catalog grains’ available stock returns to its starting value.
Process results as they arrive with WhenEach
Section titled “Process results as they arrive with WhenEach”Task: request quotes from several carriers, keep the first count quotes as they
arrive, and cancel the remaining requests.
public async DurableTask<ShippingQuote[]> CollectQuotesAsync(string route, string[] carriers, int count){ var requests = await carriers.Select(carrier => Carrier(carrier).QuoteAsync(route)) .ScheduleAll() .WithId("quotes");
var quotes = new List<ShippingQuote>(); await foreach (var request in ScheduledTask.WhenEach(requests)) { if (request.TryGetResult(out var quote) && quote is not null) { quotes.Add(quote); if (quotes.Count == count) { break; } } }
// Canceling a request which already completed changes nothing. foreach (var request in requests) { await request.CancelAsync("Enough quotes were collected."); }
return [.. quotes];}DurableTask.ScheduleAll
schedules the requests as quotes/0, quotes/1, and so on, and returns their handles.
ScheduledTask.WhenEach yields
each handle once, in completion order, including failed and canceled requests. The
runtime selects each next handle by the durable completion sequence of its result, so
every replay yields the same order and runs the same steps, including a replay in which
more requests have completed. After the loop,
ScheduledTask.CancelAsync
cancels each request with a reason; canceling a request which already completed changes
nothing.
Pitfalls:
- Base decisions on the handles which the enumeration yields. A handle which it hasn’t
yielded can report a different
IsCompletedvalue during a replay. DurableTask.WhenEachaccepts noWithId; to name the inputs, awaitScheduleAll(...).WithId(name)and enumerateScheduledTask.WhenEach(handles).- Requests which the enumeration doesn’t reach keep running until they complete, are canceled, or the task’s execution tree is deleted.
Verify: the shipping grain lists quotes/{i} for every carrier. Each request which
hadn’t completed reports the reason Enough quotes were collected. while Canceling,
then the outcome which its carrier grain reports.
Schedule now, await later with ScheduleAll
Section titled “Schedule now, await later with ScheduleAll”Task: start printing every package label, record that the order was picked while the labels print, then collect the labels.
[GenerateSerializer, Immutable]public sealed record Package(string PackageId, decimal WeightKg);
public interface ILabelGrain : IGrainWithStringKey{ DurableTask<string> PrintAsync(Package package);}
public interface IFulfillmentGrain : IGrainWithGuidKey{ DurableTask<string[]> FulfillAsync(Package[] packages);}
public sealed class FulfillmentGrain : DurableGrain, IFulfillmentGrain{ private readonly IDurableValue<bool> _picked;
public FulfillmentGrain() => _picked = StateManager.GetOrAddValue<bool>("picked");
public async DurableTask<string[]> FulfillAsync(Package[] packages) { // Starts printing every label, as the children labels/0, labels/1, and so on, without waiting for them. var labels = await packages.Select(package => GrainFactory.GetGrain<ILabelGrain>(package.PackageId).PrintAsync(package)) .ScheduleAll() .WithId("labels");
await MarkPicked().WithId("pick");
// Throws the first failure in input order, otherwise the first cancellation. await ScheduledTask.WhenAll(labels); return [.. labels.Select(label => label.GetResult())]; }
private async DurableTask<bool> MarkPicked() => _picked.Value = true;}ScheduleAll(...).WithId("labels") commits every label request with one journal write
and returns their handles without waiting. The pick step runs while the labels print.
ScheduledTask.WhenAll then
waits for every label and throws the first failure in input order, otherwise the first
cancellation, so each handle’s GetResult() returns its label.
Pitfalls:
- Await every handle, or pass it to a combinator, before the workflow returns. A label which the workflow doesn’t await keeps running, and the runtime cancels it when it deletes the task’s execution tree.
ScheduleAllruns only when awaited inside a durable execution, because its handles belong to that execution.
Verify: the fulfillment grain lists labels/{i} and pick, and the label tasks
complete in any order relative to pick.
Wait for an external event with a deadline
Section titled “Wait for an external event with a deadline”Task: wait up to three days for an approver’s decision on an expense claim.
[GenerateSerializer, Immutable]public sealed record ExpenseClaim(string EmployeeId, decimal Amount);
[GenerateSerializer, Immutable]public sealed record Decision(string ApproverId, bool Approved);
public enum ExpenseOutcome{ Approved, Rejected, Expired,}
public interface IExpenseGrain : IGrainWithGuidKey{ DurableTask<ExpenseOutcome> SubmitAsync(ExpenseClaim claim);
Task<DurableSignalResult> DecideAsync(Decision decision);}
public sealed class ExpenseGrain(IDurableTaskManager tasks) : DurableGrain, IExpenseGrain{ public static readonly DurableSignal<Decision> Decided = new("decided");
public static string SubmitTaskId(Guid expenseId) => $"expense-{expenseId:N}";
public async DurableTask<ExpenseOutcome> SubmitAsync(ExpenseClaim claim) { // Logical time, which a replay observes unchanged. var deadline = DurableTask.Current.UtcNow.AddDays(3); var (received, decision) = await Decided.TryWaitAsync(deadline).WithId("decision"); if (!received) { return ExpenseOutcome.Expired; }
return decision.Approved ? ExpenseOutcome.Approved : ExpenseOutcome.Rejected; }
public async Task<DurableSignalResult> DecideAsync(Decision decision) => await tasks.TrySignalAsync(SubmitTaskId(this.GetPrimaryKey()), Decided, decision);}TryWaitAsync races the signal with a durable
delay to the deadline and returns (true, decision) or (false, default). The task
records the first decision, and every wait and replay returns it. An ordinary grain
method delivers a decision with IDurableTaskManager.TrySignalAsync, which commits with
the grain’s pending state changes and returns a DurableSignalResult. A client sends
the same signal through the grain reference:
public static async Task<DurableSignalResult> DecideAsync(IClusterClient client, Guid expenseId, Decision decision) => await client.GetGrain<IExpenseGrain>(expenseId).TrySignalDurableTaskAsync( ExpenseGrain.SubmitTaskId(expenseId), ExpenseGrain.Decided, decision);Pitfalls:
- Compute the deadline from DurableTaskContext.UtcNow, so a replay computes the same deadline.
- Address the invoked task, here the root task which the client scheduled. A local
child’s ID isn’t an invoked task, so a signal to it returns
TaskNotFound. - Each name records one value. Use For to derive a name per occurrence of a repeated event, such as one per approval round.
- While the task runs, a decision which arrives after the deadline is recorded, and a
later
Decided.WaitAsync()in the same task returns it.
Verify: DecideAsync returns Accepted, the same decision again returns
Duplicate, a different decision returns Conflict, and a decision after the task
completed without one returns TaskCompleted.
Start follow-up work without waiting
Section titled “Start follow-up work without waiting”Task: send a receipt when an invoice is issued, without making the invoice wait for the notification service or cancel the receipt when the invoice is canceled.
[GenerateSerializer, Immutable]public sealed record InvoiceRequest(string CustomerId, decimal Amount);
public interface INotificationGrain : IGrainWithStringKey{ // Returns whether this call sent the receipt, so a repeated receipt is a no-op. DurableTask<bool> SendReceiptAsync(Guid invoiceId, decimal amount);}
public interface IInvoiceGrain : IGrainWithGuidKey{ DurableTask<decimal> IssueAsync(InvoiceRequest request);}
public sealed class InvoiceGrain : DurableGrain, IInvoiceGrain{ private readonly IDurableValue<decimal> _issued;
public InvoiceGrain() => _issued = StateManager.GetOrAddValue<decimal>("issued");
public static string ReceiptTaskId(Guid invoiceId) => $"receipt-{invoiceId:N}";
public async DurableTask<decimal> IssueAsync(InvoiceRequest request) { var amount = await Record(request.Amount).WithId("record");
// Starts the root task "receipt-{invoiceId}" on the notification grain, which commits with the invoice's result. _ = GrainFactory.GetGrain<INotificationGrain>(request.CustomerId) .SendReceiptAsync(this.GetPrimaryKey(), amount) .Detached(ReceiptTaskId(this.GetPrimaryKey())) .Post(); return amount; }
private async DurableTask<decimal> Record(decimal amount) => _issued.Value = amount;}Detached makes the call an independent
root task on the notification grain, named receipt-{invoiceId} by
WithId, and
Post stages it in the invoice grain’s
outbox. The invocation and its record in the invoice’s execution tree commit with the
invoice’s result, so a replay which reaches the record starts nothing. Observers address
the receipt by its name:
public static async Task<DurableTaskStatus> GetReceiptStatusAsync(IClusterClient client, Guid invoiceId, string customerId){ var receipt = client.GetGrain<INotificationGrain>(customerId).GetDurableTask<bool>(InvoiceGrain.ReceiptTaskId(invoiceId)); return await receipt.GetStatusAsync(new PollingOptions { PollTimeout = TimeSpan.Zero });}Pitfalls:
- Name detached tasks after stable values. Starting a different method under an existing root ID fails like other task ID reuse.
- A workflow which hands the receipt’s ID to another party before its own result commits
starts it with
ScheduleAsync, which returns once the notification grain holds it. - The notification grain retains the receipt’s result for
ResultRetentionPeriodafter completion, for polling.
Verify: the notification grain lists receipt-{invoiceId}, and the invoice grain
lists a $detach:… record beneath the invoice’s task, named by the notification grain and
the receipt’s root ID, until the invoice’s tree is deleted.
Cancel and abort from ordinary grain methods
Section titled “Cancel and abort from ordinary grain methods”Task: let the buyer cancel an order before its stock is confirmed, and let an operator abort a stuck workflow.
public async Task<bool> CancelAsync(){ if (_status.Value is not (OrderStatus.Submitted or OrderStatus.AwaitingValidation)) { return false; }
await _tasks.CancelAsync(PlaceOrderTaskId(OrderId), "Cancelled by the buyer."); return true;}
public async Task AbortAsync(string reason) => await _tasks.AbortAsync(PlaceOrderTaskId(OrderId), reason);
public async Task<bool> ShipAsync(Shipment shipment){ if (_status.Value is not OrderStatus.Paid) { return false; }
var result = await _tasks.TrySignalAsync(PlaceOrderTaskId(OrderId), Shipped, shipment); return result is DurableSignalResult.Accepted or DurableSignalResult.Duplicate;}The grain injects IDurableTaskManager, which runs against the activation’s own
runtime, without a grain call. CancelAsync(rootId, reason) completes once the request
has committed and propagated; the workflow observes it and decides its outcome, as in
the compensation recipe.
AbortAsync(rootId, reason) commits the workflow and its execution tree as failed with
DurableTaskAbortedException, whose message is the reason, and
sends an abort to each pending call to another grain. Clients use the task’s handle:
public static async Task CancelAsync(IClusterClient client, Guid orderId, string reason){ var workflow = client.GetGrain<IOrderGrain>(orderId) .GetDurableTask<OrderResult>(OrderGrain.PlaceOrderTaskId(orderId)); await workflow.CancelAsync(reason);}
public static async Task AbortAsync(IClusterClient client, Guid orderId, string reason){ var workflow = client.GetGrain<IOrderGrain>(orderId) .GetDurableTask<OrderResult>(OrderGrain.PlaceOrderTaskId(orderId)); await workflow.AbortAsync(reason);}Pitfalls:
- Check the business state before canceling. A cancellation which arrives after the workflow passed its cancellable steps runs the compensation which those steps still reach.
- Repeated cancellation requests are idempotent, and the first request’s reason is the one the workflow reads.
- Abort runs no compensation and leaves detached tasks running; abort them separately.
Verify: a canceled order’s diagnostics report its root as Completed with the
cancellation result, or Canceled when the exception escaped the workflow, with the
reason as its response. An aborted root reports Faulted with
DurableTaskAbortedException: <reason>.
Schedule a workflow from another grain or a client
Section titled “Schedule a workflow from another grain or a client”Task: start the order workflow when a buyer checks out, and observe its result.
A durable grain starts the workflow from an ordinary method with Post, which stages the invocation in its outbox, so the cleared basket and the invocation commit together in the journal write which follows:
public interface IBasketGrain : IGrainWithStringKey{ Task AddAsync(OrderLine line);
Task<Guid?> CheckoutAsync(Guid orderId, string cardLast4);
Task<OrderResult?> GetOrderResultAsync(Guid orderId);}
public sealed class BasketGrain : DurableGrain, IBasketGrain{ private readonly IDurableDictionary<int, OrderLine> _lines;
public BasketGrain() => _lines = StateManager.GetOrAddDictionary<int, OrderLine>("lines");
public async Task AddAsync(OrderLine line) { _lines[line.ProductId] = line; await WriteStateAsync(); }
public async Task<Guid?> CheckoutAsync(Guid orderId, string cardLast4) { if (_lines.Count == 0) { return null; }
var order = new SubmitOrder(this.GetPrimaryKeyString(), [.. _lines.Values], cardLast4);
_lines.Clear();
// Posts the invocation to the outbox, and the journal write commits it with the cleared basket. _ = GrainFactory.GetGrain<IOrderGrain>(orderId) .PlaceOrderAsync(order) .WithId(OrderGrain.PlaceOrderTaskId(orderId)) .Post(); await WriteStateAsync(); return orderId; }
// Polls the workflow on the order grain, which retains its result. public async Task<OrderResult?> GetOrderResultAsync(Guid orderId) { try { var response = await GrainFactory.GetGrain<IOrderGrain>(orderId) .GetDurableTask<OrderResult>(OrderGrain.PlaceOrderTaskId(orderId)) .GetResponseAsync(new PollingOptions { PollTimeout = TimeSpan.Zero }); return response.Status is DurableTaskStatus.CompletedSuccessfully ? response.GetResult<OrderResult>() : null; } catch (DurableTaskNotFoundException) { // No checkout started this order, the checkout's invocation hasn't reached the order yet, or the result's // retention period has ended. return null; } }}The workflow is a root task on the order grain, which retains it and its result for
ResultRetentionPeriod after completion, and the basket polls it there with the
GetDurableTask<TResult> grain-reference extension.
A client schedules the workflow with
ScheduleAsync, which returns once the
order grain holds the task, and awaits the returned handle, or reattaches to it later by
root ID with GetDurableTask<TResult>:
public static async Task<OrderResult> PlaceOrderAsync(IClusterClient client, Guid orderId, SubmitOrder order){ // Scheduling the same request under the same root ID again returns the same task, so a retry is safe. ScheduledTask<OrderResult> workflow = await client.GetGrain<IOrderGrain>(orderId) .PlaceOrderAsync(order) .WithId(OrderGrain.PlaceOrderTaskId(orderId)) .ScheduleAsync(); return await workflow;}
public static async Task<DurableTaskStatus> GetStatusAsync(IClusterClient client, Guid orderId){ var workflow = client.GetGrain<IOrderGrain>(orderId) .GetDurableTask<OrderResult>(OrderGrain.PlaceOrderTaskId(orderId)); return await workflow.GetStatusAsync(new PollingOptions { PollTimeout = TimeSpan.Zero });}A PollingOptions value with a zero PollTimeout returns the
current status at once; a longer timeout waits up to that time for completion. Inside a
durable task, awaiting the call runs it as a child, and WithId(name).ScheduleAsync()
starts a child and returns its handle to await later.
Pitfalls:
- Derive the root ID from a business identity, such as the order ID, with
WithId, so a retried checkout reaches the same task instead of starting a second workflow. - A root task is retained for
ResultRetentionPeriodafter completion. Later polls throwDurableTaskNotFoundException, and starting the same root ID again runs the workflow again.
Verify: the order grain lists place-order-{orderId}, the basket lists no task for
it, and GetOrderResultAsync returns the result after the order ships.
