Click here to Skip to main content
15,881,803 members
Articles / Programming Languages / C#

A .NET State Machine Toolkit - Part III

Rate me:
Please Sign up or sign in to vote.
4.91/5 (43 votes)
26 Oct 2006CPOL11 min read 223.4K   1.2K   135  
Using code generation with the .NET state machine toolkit.
/*
 * Created by: Leslie Sanford
 * 
 * Contact: jabberdabber@hotmail.com
 * 
 * Last modified: 10/06/2005
 */

using System;
using System.ComponentModel;
using System.Threading;
using LSCollections;

namespace StateMachineToolkit
{
    /// <summary>
    /// Represents an asynchronous event queue.
    /// </summary>
    public sealed class EventQueue : IComponent
    {
        #region EventQueue Members

        #region Fields

        // The thread for processing events.
        private Thread eventThread;

        // The deque for enqueueing and dequeueing events.
        private Deque eventDeque = Deque.Synchronized(new Deque());

        // The object to use for locking.
        private readonly object lockObject = new object();

        // Inidicates whether the event queue has been disposed.
        private volatile bool disposed = false;

        private ISite site = null;

        #endregion

        #region Construction

        /// <summary>
        /// Initializes a new instance of the EventQueue class.
        /// </summary>
        public EventQueue()
        {
            // Create thread for processing events.
            eventThread = new Thread(new ThreadStart(EventProcedure));

            lock(lockObject)
            {
                eventThread.Start();

                // Wait for signal from thread that it is running.
                Monitor.Wait(lockObject);
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Sends an event to the specified state machine.
        /// </summary>
        /// <param name="target">
        /// The state machine to send the event to.
        /// </param>
        /// <param name="eventID">
        /// The event's ID.
        /// </param>
        /// <param name="args">
        /// The event's arguments.
        /// </param>
        /// <exception cref="ObjectDisposedException">
        /// If the EventQueue has already been disposed.
        /// </exception>
        public void Send(StateMachine target, int eventID, params object[] args)
        {
            #region Preconditions

            if(disposed)
            {
                throw new ObjectDisposedException("EventQueue");
            }

            #endregion

            lock(lockObject)
            {
                StateMachineEventArgs e = 
                    new StateMachineEventArgs(target, eventID, args);

                eventDeque.PushBack(e);

                // Signal the event thread that an event has been sent.
                Monitor.Pulse(lockObject);
            }
        }

        /// <summary>
        /// Sends and event to the front of the EventQueue.
        /// </summary>
        /// <param name="target">
        /// The state machine to send the event to.
        /// </param>
        /// <param name="eventID">
        /// The event's ID.
        /// </param>
        /// <param name="args">
        /// The event's arguments.
        /// </param>
        /// <exception cref="ObjectDisposedException">
        /// If the EventQueue has already been disposed.
        /// </exception>
        public void SendPriority(StateMachine target, int eventID, params object[] args)
        {
            #region Preconditions

            if(disposed)
            {
                throw new ObjectDisposedException("EventQueue");
            }

            #endregion

            lock(lockObject)
            {
                StateMachineEventArgs e = 
                    new StateMachineEventArgs(target, eventID, args);

                eventDeque.PushFront(e);

                // Signal the event thread that an event has been sent.
                Monitor.Pulse(lockObject);
            }
        }

        // Processes and dispatches events.
        private void EventProcedure()
        {
            StateMachineEventArgs e;

            lock(lockObject)
            {
                // Signal the constructor that the thread is now running.
                Monitor.Pulse(lockObject);

                // While the event queue has not been disposed.
                while(!disposed)
                {
                    // Wait for next event.
                    Monitor.Wait(lockObject);                    

                    // While the event queue has not been disposed and there
                    // are still events in the queue.
                    while(!disposed && eventDeque.Count > 0)
                    {
                        // Get the next event argument.
                        e = (StateMachineEventArgs)eventDeque.PopFront();

                        // Dispatch event to the target state machine.
                        e.Target.Dispatch(e.EventID, e.Args);
                    }                    
                }

                OnDisposed();
            }
        }

        private void OnDisposed()
        {
            EventHandler handler = Disposed;

            if(handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }

        #endregion

        #endregion

        #region IComponent Members

        /// <summary>
        /// Represents the method that handles the Disposed event of an EventQueue.
        /// </summary>
        public event System.EventHandler Disposed;

        /// <summary>
        /// Gets or sets the ISite associated with the EventQueue.
        /// </summary>
        public ISite Site
        {
            get
            {
                return site;
            }
            set
            {
                site = value;
            }
        }

        #endregion

        #region IDisposable Members

        /// <summary>
        /// Disposes of the EventQueue.
        /// </summary>
        public void Dispose()
        {
            #region Guards

            if(disposed)
            {
                return;
            }

            #endregion

            lock(lockObject)
            {
                disposed = true;

                Monitor.Pulse(lockObject);
            }
        }

        #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