Instantiating and using offline state machines

Offline state machines are created by invoking a static method of the factory class. Each offline state machine will need to have its optional error and debug output streams opened and attached after creation, if needed. Similarly, each offline state machine instance will need to have an input event source created and attached by passing a reference to it as an argument to the Run method of the state machine.

In all other respects, the offline state machine behaves and is programmed like the in-line state machine. A simple example showing the creation and use of two FSMs is given below:


public void DemoTwoFSMs(TextReader input1, TextReader input2)
{
    // Create and use the first state machine
    
    MyFSM p = FSMFactory<MyFSM>.CreateInstance();
    p.ErrStream = new StringWriter();
    MyTokeniser t = new MyTokeniser(input1, p.Tokens);
    bool result1 = p.Run(t);
    
    // Create a second state machine
    
    MyFSM q = FSMFactory<MyFSM>.CreateInstance();
    q.ErrStream = new StringWriter();
    MyTokeniser u = new MyTokeniser(input2, q.Tokens);
    bool result2 = q.Run(u);
}    

Careful use of thread pooling, or demultiplexing of input tokens based on which FSM they should be fed to, can enable the use of multiple state machines in the same application for workflow scenarios very easily. Note that a state machine itself is not written to be thread safe, but shares no writable data structures with other state machines while it is running, as the shared FSM data tables are read only. Hence multiple state machines can be used within the same application each on a separate thread provided you take care to ensure thread safety among the application-specific parts of your FSM class and other application classes.