The C# state machine context

The context class is the fundamental class generated and directly used by your code. The following documentation explains how the context class is named, what are the constructor parameters, how to perform the second phase initialization with EnterInitialState(), and finally, how to find out that the context has ended.

Context name

By default the context class name is based on the filename without extension, then it is suffixed by "Context":

MyStateMachine.fsmcs => MyStateMachineContext

It is also possible to set the context class name with the context element:

Context contructor

The constructor parameters are defined by the object tag in the settings element:

Here is the C# code that shows how to create an instance of the context:


After the creation of an instance of the context, one may invoke the method EnterInitialState() to call the OnEntry() methods from the root state to the initial state.

Consider the Led state machine example:

In this case, EnterInitialState() will call led.DoOff() to make sure the led is switched off.

Context ending and final state

Final states are state which have the attribute kind set to final:

When the machine enters a final state, the context fires the event EndHandler

Consider the example below, a private function called StateMachineEnd is registered to the event handler and will be called when the context reaches a final state.

A AutoResetEvent class is used to synchronize the main thread.