Click or drag to resize
StaMaStateMachineSaveState Method
Saves the state machine active state and history to a Stream that may be used to resume with this state later e.g. after the hosting process has been restarted.

Namespace: StaMa
Assembly: StaMa (in StaMa.dll) Version: 2.3.1.7
Syntax
public void SaveState(
	Stream outputStream
)

Parameters

outputStream
Type: System.IOStream
A Stream that receives the serialized ActiveStateConfiguration and history states.
Exceptions
ExceptionCondition
ArgumentNullExceptionThe outputStream parameter is null
ArgumentExceptionThe outputStream cannot be written.
StateMachineExceptionThis StateMachine instance is not yet started or already finished and thus has no valid ActiveStateConfiguration.
Remarks
The data written to the outputStream is used as the input for the Resume(Stream, Boolean) method.
Examples

The following code shows how to use the SaveState and Resume methods:

SaveState and Resume
StateMachineTemplate t = new StateMachineTemplate();
t.Region("State1", false);
    t.State("State1");
        t.Transition("T1", "State2", "Event1");
    t.EndState();
    t.State("State2");
        t.Transition("T2", "State1", "Event2");
    t.EndState();
t.EndRegion();

// Create a state machine and start it
StateMachine stateMachine1 = t.CreateStateMachine();
stateMachine1.Startup();

// stateMachine1 is now ready for receiving events
stateMachine1.SendTriggerEvent("Event1");
// Check that stateMachine1 has executed transition "T1" to state "State2"
if (stateMachine1.ActiveStateConfiguration.ToString() != t.CreateStateConfiguration("State2").ToString())
{
    throw new Exception("stateMachine1 in unexpected state");
}

// Save the current state of stateMachine1
MemoryStream stream = new MemoryStream();
stateMachine1.SaveState(stream);
stream.Flush(); // Might write to persistent storage when using FileStream instead

// For demonstration purposes reset the MemoryStream to enable reading from it
// Real applications would open a FileStream
stream.Position = 0;

// Create a new state machine using the same structure and resume from saved state
StateMachine stateMachine2 = t.CreateStateMachine();
stateMachine2.Resume(stream, false);

// stateMachine2 is ready for receiving events
stateMachine2.SendTriggerEvent("Event2");
// Check that stateMachine2 has executed transition "T2" to state "State1"
if (stateMachine2.ActiveStateConfiguration.ToString() != t.CreateStateConfiguration("State1").ToString())
{
    throw new Exception("stateMachine2 in unexpected state");
}
See Also