dotnet-state-machine / stateless

A simple library for creating state machines in C# code
Other
5.62k stars 767 forks source link

Automatic transition from one state to another #602

Open mkulisic opened 1 month ago

mkulisic commented 1 month ago

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?