Skip to content

Automatic transition from one state to another #602

@mkulisic

Description

@mkulisic

Hello,
I'm trying to figure out if there is a proper way to handle automatic transitions between states. So for example, I'd like to have 3 states (Start, Processing, and End). I've seen a few suggestions online that say I could leverage the .OnEntry or .OnEntryAsync() to achieve this behavior and it would look something like this:

public class Process
{
    private readonly StateMachine<State, Trigger> _machine;

    public Process()
    {
        _machine = new StateMachine<State, Trigger>(State.Start);

        _machine.Configure(State.Start)
            .Permit(Trigger.StartProcessing, State.Processing);

        _machine.Configure(State.Processing)
            .OnEntry(DoWork)
            .Permit(Trigger.WorkCompleted, State.End);

        _machine.Configure(State.End)
            .OnEntry(() => Console.WriteLine("Process completed."));
    }

    public void Start()
    {
        _machine.Fire(Trigger.StartProcessing);
    }

    private void DoWork()
    {
        Console.WriteLine("Processing...");
        System.Threading.Thread.Sleep(2000); // Simulate work with a delay
        _machine.Fire(Trigger.WorkCompleted);
    }

    public State CurrentState => _machine.State;
}

Is this a valid use of the OnEntry method or could this cause any issues during transitions?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions