Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write state machines with c#?

I need to write state machines that run fast in c#. I like the Windows Workflow Foundation library, but it's too slow and over crowded with features (i.e. heavy). I need something faster, ideally with a graphical utility to design the diagrams, and then spit out c# code. Any suggestions? Thanks!

like image 769
Nestor Avatar asked Oct 04 '09 19:10

Nestor


2 Answers

Ultimately, you probably want the newly redesigned WF engine in .NET 4.0, as it is much faster and provides a flowchart activity (not quite a state machine, but works for most scenarios) and a nice designer UI experience. But since it's not yet released, that is probably not a good answer for now.

As an alternative, you could try stateless, a library specifically for creating state machine programs in .NET. It doesn't appear to provide a UI, but looks well-suited to fulfill your other goals.

like image 198
bobbymcr Avatar answered Oct 09 '22 11:10

bobbymcr


Yeah, Microsoft may have been ahead of their time with State Machine WF. Sequential Workflows are being received much better.

When we decided on using a state machine, we rolled our own. because we couldn't find an acceptable framework with a UI. Here are our steps. Hope they'll help you.

  1. Create your state interface:

    public interface IApplicationState
    {
        void ClickOnAddFindings();        
        void ClickOnViewReport();
        //And so forth
    }
    
  2. Create the states and have them implement the interface:

    public class AddFindingsState : IApplicationState
    {
        frmMain _mForm;
    
        public AddFindingsState(frmMain mForm)
        {
            this._mForm = mForm;
        }
    
        public void ClickOnAddFindings()
        {            
        }
    
        public void ClickOnViewReport()
        {
            // Set the State
            _mForm.SetState(_mForm.GetViewTheReportState());
        }
    }
    
  3. Instantiate the states in your main class.

    IApplicationState _addFindingsState;
    IApplicationState _viewTheReportState;
    _addFindingsState = new AddFindingsState(this);
    _viewTheReportState = new ViewTheReportState(this);
    
  4. When the user does something requiring a change of state, call the methods to set the state:

    _state.ClickOnAFinding();
    

Of course, the actions will live in the particular instance of the IApplicationState.

like image 36
Rap Avatar answered Oct 09 '22 13:10

Rap