How to write state machines with c#?
Solution 1
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.
Solution 2
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.
-
Create your state interface:
public interface IApplicationState { void ClickOnAddFindings(); void ClickOnViewReport(); //And so forth }
-
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()); } }
-
Instantiate the states in your main class.
IApplicationState _addFindingsState; IApplicationState _viewTheReportState; _addFindingsState = new AddFindingsState(this); _viewTheReportState = new ViewTheReportState(this);
-
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.
Related videos on Youtube
Nestor
Systems Engineer, with a Masters in Computational Finance from Carnegie Mellon University. Writing software is one of the pleasures of life!
Updated on June 17, 2020Comments
-
Nestor about 4 years
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!
-
Nestor over 14 yearsInteresting implementation. Thanks for sharing.
-
Jonathan Oliver almost 14 years+1 for stateless. It's a great little library and a breath of fresh air compared to Workflow Foundation (even WF 4.0).