AsyncStateMachine 1.3.2

dotnet add package AsyncStateMachine --version 1.3.2                
NuGet\Install-Package AsyncStateMachine -Version 1.3.2                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="AsyncStateMachine" Version="1.3.2" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add AsyncStateMachine --version 1.3.2                
#r "nuget: AsyncStateMachine, 1.3.2"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install AsyncStateMachine as a Cake Addin
#addin nuget:?package=AsyncStateMachine&version=1.3.2

// Install AsyncStateMachine as a Cake Tool
#tool nuget:?package=AsyncStateMachine&version=1.3.2                

AsyncStateMachine Continuous NuGet Status

A framework for creating state machines and lightweight state machine-based workflows for Microsoft .NET

// Create a state machine configuration with the initial Open state.
var config = new StateMachineConfiguration<Trigger, State>(State.Open);

// Configure the Open state
config.Configure(State.Open)
    .Permit(Trigger.assign, State.Assigned);

// Configure the Assigned state
config.Configure(State.Assigned)
    .PermitReentry(Trigger.assign)
    .Permit(Trigger.close, State.Closed)
    .Permit(Trigger.defer, State.Deferred)
    .OnEntry<string>(assignee => OnAssignedAsync(assignee)) // asynchronous with parameter
    .OnExit(OnDeassignedAsync); // asynchronous without parameter

// Configure the Deferred state
config.Configure(State.Deferred)
    .OnEntry(() => _assignee = null) // synchronous
    .Permit(Trigger.assign, State.Assigned);

// Configure the Closed state
config.Configure(State.Closed)
    .OnEntry(() => Console.WriteLine("Bug is closed"));

// ...

// Instantiate a new state machine using the previously created configuration.
var stateMachine = new StateMachine<Trigger, State>(config);

// initialize the state machine to invoke the OnEntry callback for the initial state.
await stateMachine.IntializeAsync();

await stateMachine.FireAsync(Trigger.assign); // asynchronous
Assert.AreEqual(State.Assigned, stateMachine.CurrentState);

This project, as well as the example above, was inspired by Stateless. The aim of this project is not to provide a one-to-one replacement of stateless. The goal was to provide a state machine providing an asynchronous interface, lightweight implementation, easy to maintain and easy to extend.

Features

Most standard state machine constructs are supported:

  • Generic support for states and triggers of type struct (numbers, chars, enums, etc.)
  • Entry/exit actions for states (synchronous and asynchronous)
  • Guard clauses to support conditional transitions
  • Hierarchical states
  • Unit tested (code coverage >80%)

Some useful extensions are also provided:

  • Parameterized triggers
  • Reentrant states
  • Export state machine as graph (Graphviz/DOT, Mermaid Flow-Chart or Mermaid State-Diagram)

Entry/Exit actions

// Configure the Assigned state
config.Configure(State.Assigned)
    .Permit(Trigger.assign, State.Assigned)
    .Permit(Trigger.close, State.Closed)
    .Permit(Trigger.defer, State.Deferred)
    .OnEntry<string>(assignee => OnAssignedAsync(assignee)) // asynchronous with parameter
    .OnExit(OnDeassignedAsync); // asynchronous without parameter

Entry/Exit actions can be used to apply certain functionality when a certain state is reached. The OnEntry() calls are all invoked when the state is reached and all OnExit() calls are invoked, when the state is changed. OnEntry() calls support synchronous and asynchronous functions as well as parameterized versions. Currently, only a single parameter is supported. If several parameters are needed, then these must be encapsulated in a class/struct/pair. When multiple OnEntry/OnExit callbacks are registered, then all of them are executed in the order of registration.

Guard Clauses

The state machine will choose between multiple transitions based on guard clauses, e.g.:

config.Configure(State.SomeState)
    .PermitIf(Trigger.ab, State.A, () => Condition)
    .PermitIf(Trigger.ab, State.B, () => !Condition);

Depending on the guard clause, the trigger either transitions to state A or state B. Guard clauses within a state must be mutually exclusive (multiple guard clauses cannot be valid at the same time). The guard clauses will be evaluated whenever a trigger is fired. Guards should therefor be made side effect free.

Parameterised Triggers

A strongly-typed parameter can be assigned to trigger:

config.Configure(State.Assigned)
    .OnEntry<string>(email => OnAssigned(email));

// ...

await stateMachine.FireAsync(assignTrigger, "john.doe@example.com");

If no callback can be found handling the given type of argument, an ArgumentException is thrown. If multiple parameters have to be passed into the attached callback, then wrap the parameters into a new class and pass a strongly-typed instance of that class into the FireAsync() call. It doesn't matter if the callback is synchronous or asynchronous, both versions are supported out of the box.

Ignored Transitions and Reentrant States

Firing a trigger that does not have an allowed transition associated with it will cause an exception (InvalidOperationException) to be thrown.

To ignore triggers within certain states, use the Ignore(...) directive:

config.Configure(State.Closed)
    .Ignore(Trigger.close);

Alternatively, a state can be marked reentrant so its entry and exit actions will fire even when transitioning from/to itself:

config.Configure(State.Assigned)
    .PermitReentry(Trigger.assign)
    .OnEntry(() => SendEmailToAssignee());

By default, triggers must be ignored explicitly. Otherwise an exception (InvalidOperationException) is thrown.

State Hierarchy

config.Configure(State.A);
config.Configure(State.B)
    .SubstateOf(A);
config.Configure(State.C)
    .SubstateOf(B);

Defines a multi-level hierarchy where C and B are sub-states of A. The CurrentState property always returns the current state. But with InStateAsync(...) can be checked, if the machine is in a sub-state and in the super-/parent-state.

The max. supported depth of hierarchies is limited to InStateAsync(...) by ushort.MaxValue = 65535.

Observation

AsyncStateMachine provides an observable to propagate state changes:

IDisposable subscription = stateMachine.Observable.Subscribe(
    (source, trigger, destination) => Console.WriteLine($"{source} --{trigger}--> {destination}"));

// ...

subscription.Dispose();

The observable is invoked, whenever the state machine state has changed.

Export as graph

It can be useful to visualize state machines. With this approach the code is the authoritative source and state diagrams are always up-to-date. Therefore AsyncStateMachine supports different graph engines like: Graphviz and Mermaid

Graphviz
string graph = DotGraph.Format(config, GraphOptions.Default);

The DotGraph.Format() method returns a string representation of the state machine in the DOT graph language.

This can then be rendered by tools that support the DOT graph language, such as the dot command line tool from graphviz.org or use http://www.webgraphviz.com for instant viewing.

The rendered bug StateMachine looks like this: alternate text is missing from this package README image

Mermaid
string graph = MermaidStateGraph.Format(config);

The rendered mermaid state graph looks like this: alternate text is missing from this package README image

or

string graph = MermaidFlowChartGraph.Format(config);

The rendered mermaid flow graph looks like this: alternate text is missing from this package README image

The Mermaid*Graph.Format() methods return a string representation of the state machine in the Mermaid graph language).

This string representation can then be rendered by tools that support the mermaid graph language, such as Azure DevOPS or https://mermaid.live for instant viewing.

Building

AsyncStateMachine runs on .NET NetCore platforms targeting .NET 6.0 or 7.0. Visual Studio 2022 or Visual Code is required to build the solution.

Project Goals

This page is an almost-complete description of AsyncStateMachine, and its explicit aim is to remain minimal.

Please use the issue tracker if you'd like to report problems or discuss features.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.3.2 1,801 12/11/2023
1.3.1 1,121 9/16/2022
1.3.0 505 9/10/2022
1.2.0 527 9/5/2022
1.1.2 723 8/23/2022
1.1.1 458 8/22/2022
1.1.0 4,920 12/24/2021
1.0.1 311 12/23/2021
1.0.0 285 12/22/2021