Skip to content

5.1. Behavior Values

Mikołaj Milewski edited this page Nov 12, 2026 · 1 revision

Behavior Values and State-Scoped Values

Every Behavior context exposes a Values collection: an asynchronous, typed key-value store for implementation data owned by that Behavior instance. State Machines also expose a separate Values collection for each State, including composite and orthogonal states. Use these collections for internal execution data, not as a substitute for an Entity's domain fields, mutation contract, or projections.

Values are isolated by Behavior identity; they are not shared with another Behavior in a behavioral group. Use an Entity to share durable domain data between related Behaviors.

Behavior-wide Values

Use context.Behavior.Values from an action, transition, initializer, or other Behavior context:

.AddInitialState("Receiving", state => state
    .AddOnEntry(async context =>
    {
        await context.Behavior.Values.SetAsync("upload.started", true);
        await context.Behavior.Values.UpdateAsync<int>(
            "upload.chunk-count",
            count => count + 1,
            defaultValue: 0);
    })
    .AddTransition<Finish>("Completed")
)

Read a value with TryGetAsync<T> when absence matters, or use GetOrDefaultAsync<T> when a default is appropriate:

var (found, count) =
    await context.Behavior.Values.TryGetAsync<int>("upload.chunk-count");

var completed =
    await context.Behavior.Values.GetOrDefaultAsync("upload.completed", false);

IContextValues provides these asynchronous operations:

Method Purpose
SetAsync<T>(key, value) Store or replace a value.
TryGetAsync<T>(key) Read a value as (Success, Value); returns Success == false if absent or incompatible with T.
GetOrDefaultAsync<T>(key, defaultValue) Read a value or return the supplied default.
IsSetAsync(key) Check whether the key exists.
UpdateAsync<T>(key, updater, defaultValue) Read, transform, and store a value using a default when absent.
RemoveAsync(key) Remove one value.
HasAnyPrefixedAsync(prefix) Check for keys beginning with a prefix.
RemovePrefixedAsync(prefix) Remove all keys beginning with a prefix.
ClearAsync() Remove all values from this collection.

Values are serialized as part of the Behavior's context, so store values supported by the configured Stateflows serialization and persistence setup. Reads deserialize stored data; for mutable reference types, modify the retrieved value and call SetAsync (or UpdateAsync) to persist the change. Use stable, namespaced keys (for example, upload.chunk-count) to avoid collisions between independent pieces of Behavior logic.

Behavior-wide Values remain available as the Behavior moves between States and are not automatically cleared on State exit. They are part of the Behavior context; their durability across process restarts depends on the runtime's context persistence configuration. A State Machine's internal reset clears its execution-state context, not necessarily its separate Behavior-wide Values collection; explicitly remove or clear values when the model requires that behavior.

Activity streaming values

During an Orleans Activity streaming busy period, transactional, mixed, and streamed branches use the same live Behavior.Values collection. All branches may read and write it. Individual operations are synchronized; several operations across keys or separated by await are not an isolated transaction.

Use UpdateAsync for a single-key read-modify-write instead of separate read/set operations. A value captured in a local variable, or injected as a plain T, is still a snapshot; other branches do not update that local automatically.

Already-applied value changes remain visible even if a regular event fails while streaming is live. The engine does not roll those changes back. Values and network marking become durable together only at natural quiescence or an Activity checkpoint, not merely because a regular event or publication committed.

After natural quiescence ends the streaming busy period, later ordinary Activity calls return to ordinary successful-call commit and failed-call rollback semantics. Activity reset clears its global values and marking. A reset with a Checkpoint header drains active firing bodies to a barrier and discards their ready successors.

Mutations through a cancelled Activity scope are ignored, including SetAsync, updates, removals, and clears. Values written before cancellation remain visible to the finalizer. This fences late engine writes; it does not stop external effects performed by non-cooperative application code.

Treat streaming values as live configuration/coordination data, not an atomic durable business ledger. Report durable business completion through an application-owned contract or storage operation.

State-scoped Values

In a State action, use context.State.Values to keep data with that State rather than the whole State Machine:

.AddState("Retrying", state => state
    .AddOnEntry(async context =>
    {
        await context.State.Values.UpdateAsync<int>(
            "attempts",
            attempts => attempts + 1,
            defaultValue: 0);
    })
    .AddTransition<RetrySucceeded>("Succeeded")
)

State-scoped Values are keyed by State identity/name within the State Machine. A child state can access its parent State's collection through context.State.TryGetParent(out var parent):

if (context.State.TryGetParent(out var parent))
{
    var (found, phase) = await parent.Values.TryGetAsync<string>("phase");
}

On a transition, inspect the source or target State collections through the transition context:

.AddTransition<RetrySucceeded>("Succeeded", transition => transition
    .AddGuard(async context =>
    {
        var (found, attempts) =
            await context.Source.Values.TryGetAsync<int>("attempts");
        return found && attempts < 5;
    })
)

For a target State, use context.Target?.Values; it can be absent for an internal transition. Declarative helpers are also available, for example Guards.Source.Value("attempts").IsEqualTo(3) and Guards.Target.Value("mode").IsSet.

State-scoped data normally belongs to the State's active lifetime: Stateflows clears it when that State is exited. If the containing region has History enabled, the State's Values are retained with the saved configuration so history restoration can resume the State with its data. A self-transition that leaves the State active does not clear its values.

Constructor injection

Model-element constructor parameters can receive a value or an IValue<T> accessor. The attribute chooses the collection and the key; when name is omitted, the constructor parameter name is used:

using Stateflows.Common;
using Stateflows.Common.Attributes;
using Stateflows.StateMachines.Attributes;

public sealed class RetryCounter(
    [GlobalValue("upload.total")] IValue<int> total,
    [StateValue("attempts")] IValue<int> attempts)
{
    public async Task IncrementAsync()
    {
        await total.UpdateAsync(value => value + 1, 0);
        await attempts.UpdateAsync(value => value + 1, 0);
    }
}

[GlobalValue] selects the Behavior-wide collection. In a State Machine, [StateValue] selects the current State's collection, and [ParentStateValue] selects the containing State's collection. On transition-related model elements, [SourceStateValue] and [TargetStateValue] select the corresponding endpoint's collection. These State-specific attributes are in Stateflows.StateMachines.Attributes.

Injecting IValue<T> provides an accessor that reads or updates the selected key when its methods are called. Injecting a plain T reads the value during model-element activation; it is a snapshot, not a live binding. If a value may not exist yet, use IValue<T>.TryGetAsync() or mark a plain injected parameter required: false and provide an optional/default value.

Choosing Values or an Entity

Use Appropriate storage
Private implementation counter, checkpoint, or coordination flag for one Behavior instance Behavior.Values
Data belonging to one State's active/history-restorable configuration State.Values
Domain data shared by multiple Behaviors, queried as a read model, or changed through domain operations Entity fields, mutations, and projections

Values are not a public domain schema and do not publish change notifications. Although code running in a Behavior context can access Behavior.Values, this is not a typed domain API for clients or sibling Behaviors. Use Events for behavior communication and Entities for shared domain state.

Clone this wiki locally