Click here to Skip to main content
15,886,199 members
Articles / Programming Languages / C#

A .NET State Machine Toolkit - Part I

Rate me:
Please Sign up or sign in to vote.
4.80/5 (69 votes)
29 Mar 2007CPOL18 min read 410K   2.5K   290  
An introduction to the .NET State Machine Toolkit.
/*
 * Created by: Leslie Sanford
 * 
 * Contact: jabberdabber@hotmail.com
 * 
 * Last modified: 11/08/2005
 */

using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;

namespace StateMachineToolkit
{
	/// <summary>
	/// Represents the base class for all state machines.
	/// </summary>
	public abstract class StateMachine
	{
        #region StateMachine Members

        #region Fields

        // The ISynchronizeInvoke object for dispatching events.
        private ISynchronizeInvoke synchronizingObject = null;

        // The current state.
        private State currentState = null;

        // Represents the method that dispatches events to states.
        private DispatchCallback dispatchMethod;

        // The return value of the last action.
        private object actionResult;

        // Indicates whether the state machine is in the middle of a state transition.
        private bool transitioning = false;

        #endregion

        #region Delegates

        // Represents the method used for dispatching events to the current state.
        private delegate object DispatchCallback(int eventID, object[] args);

        #endregion

        #region Construction

        /// <summary>
        /// Initializes a new instance of the StateMachine class.
        /// </summary>
        public StateMachine()
        {
            dispatchMethod = new DispatchCallback(Dispatch);
        }

        #endregion

        #region Methods

        /// <summary>
        /// Initializes the StateMachine's initial state.
        /// </summary>
        /// <param name="initialState">
        /// The state that will initially receive events from the StateMachine.
        /// </param>
        protected void Initialize(State initialState)
        { 
            State superstate = initialState;
            Stack superstateStack = new Stack();           

            // If the initial state is a substate, travel up the state 
            // hierarchy in order to descend from the top state to the initial
            // state.
            while(superstate != null)
            {
                superstateStack.Push(superstate);
                superstate = superstate.Superstate;
            }

            // While there are superstates to traverse.
            while(superstateStack.Count > 0)
            {
                superstate = (State)superstateStack.Pop();
                superstate.Entry();
            }

            currentState = initialState.EnterByHistory();
        }

        /// <summary>
        /// Sends an event to the StateMachine.
        /// </summary>
        /// <param name="eventID">
        /// The event ID.
        /// </param>
        /// <param name="args">
        /// The data accompanying the event.
        /// </param>
        /// <returns>
        /// </returns>
        protected IAsyncResult Send(int eventID, params object[] args)
        {
            #region Preconditions

            if(eventID < 0)
            {
                throw new ArgumentOutOfRangeException("eventID", eventID,
                    "Event ID out of range.");
            }

            #endregion

            IAsyncResult result = null;

            // If a synchronizing object is being used.
            if(synchronizingObject != null)
            {
                // Dispatch the event asynchronously.
                result = synchronizingObject.BeginInvoke(dispatchMethod, new object[] { eventID, args });
            }
            // Else no synchronizing object is being used.
            else
            {
                Debug.Assert(!transitioning, "State transition error.",
                    "An attempt was made to send an event to the state machine " +
                    "synchronously while it is in the middle of a " +
                    "state transition.");

                result = EmptyAsyncResult.Instance;

                Dispatch(eventID, args);
            }

            return result;
        }

        /// <summary>
        /// Sends events to the StateMachine synchronously.
        /// </summary>
        /// <param name="args">
        /// The arguments accompanying the event.
        /// </param>
        /// <returns>
        /// The result of the action, if one was performed; otherwise, null.
        /// </returns>
        protected object SendSynchronously(int eventID, params object[] args)
        {
            #region Preconditions

            if(eventID < 0)
            {
                throw new ArgumentOutOfRangeException("eventID", eventID,
                    "Event ID out of range.");
            }

            #endregion

            // If a synchronizing object is being used.
            if(synchronizingObject != null)
            {
                // If the event was sent from another thread.
                if(synchronizingObject.InvokeRequired)
                {
                    // Dispatch the event synchronously.
                    synchronizingObject.Invoke(dispatchMethod, new object[] { eventID, args });
                }
                // Else the event was sent on this thread.
                else
                {
                    Debug.Assert(!transitioning, "State transition error.",
                        "A state machine cannot send an event to itself " +
                        "synchronously while it is in the middle of a " +
                        "state transition.");

                    Dispatch(eventID, args);
                }
            }
            // Else no synchronizing object is being used.
            else
            {
                Debug.Assert(!transitioning, "State transition error.",
                    "An attempt was made to send an event to the state machine " +
                    "synchronously while it is in the middle of a " +
                    "state transition.");

                Dispatch(eventID, args);
            }

            return ActionResult;
        }
        
        /// <summary>
        /// Dispatches events to the current state.
        /// </summary>
        /// <param name="eventID">
        /// The event ID.
        /// </param>
        /// <param name="args">
        /// The data accompanying the event.
        /// </param>
        internal object Dispatch(int eventID, object[] args)
        {
            // Indicate that a transition is taking place.
            transitioning = true;

            // Reset action result.
            ActionResult = null;

            TransitionResult result;

            // Dispatch event to the current state.
            result = currentState.Dispatch(eventID, args);

            // If a transition was fired as a result of this event.
            if(result.HasFired)
            {
                // Set new current state.
                currentState = result.NextState;

                // Indicate that the transition is over.
                transitioning = false;

                // If an exception occurred as a result of the transition.
                if(result.HasExceptionOccurred)
                {
                    throw new ApplicationException("Exception occurred in state machine.", result.Exception);
                }
            }
            // Else no transition fired.
            else
            {
                // Indicate that the transition is over.
                transitioning = false;
            }

            return ActionResult;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the ISynchronizeObject to use for dispatching events.
        /// </summary>
        public virtual ISynchronizeInvoke SynchronizingObject
        {
            get
            {
                return synchronizingObject;
            }
            set
            {                
                synchronizingObject = value;
            }
        }

        /// <summary>
        /// Gets or sets the results of the action performed during the last transition.
        /// </summary>
        /// <remarks>
        /// This property should only be set during the execution of an action method.
        /// </remarks>
        protected object ActionResult
        {
            get
            {
                return actionResult;
            }
            set
            {
                actionResult = value;
            }
        }

        #endregion

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Aside from dabbling in BASIC on his old Atari 1040ST years ago, Leslie's programming experience didn't really begin until he discovered the Internet in the late 90s. There he found a treasure trove of information about two of his favorite interests: MIDI and sound synthesis.

After spending a good deal of time calculating formulas he found on the Internet for creating new sounds by hand, he decided that an easier way would be to program the computer to do the work for him. This led him to learn C. He discovered that beyond using programming as a tool for synthesizing sound, he loved programming in and of itself.

Eventually he taught himself C++ and C#, and along the way he immersed himself in the ideas of object oriented programming. Like many of us, he gotten bitten by the design patterns bug and a copy of GOF is never far from his hands.

Now his primary interest is in creating a complete MIDI toolkit using the C# language. He hopes to create something that will become an indispensable tool for those wanting to write MIDI applications for the .NET framework.

Besides programming, his other interests are photography and playing his Les Paul guitars.

Comments and Discussions