Click here to Skip to main content
15,896,063 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 411.7K   2.5K   290  
An introduction to the .NET State Machine Toolkit.
#region License

/* Copyright (c) 2006 Leslie Sanford
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to 
 * deal in the Software without restriction, including without limitation the 
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 
 * sell copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software. 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 * THE SOFTWARE.
 */

#endregion

#region Contact

/*
 * Leslie Sanford
 * Email: jabberdabber@hotmail.com
 */

#endregion

using System;
using System.Collections;
using System.ComponentModel;
using System.Threading;

namespace StateMachineToolkit
{
    /// <summary>
    /// Represents an asynchronous queue of delegates.
    /// </summary>
    public sealed class DelegateQueue : IComponent, ISynchronizeInvoke
    {
        #region DelegateQueue Members

        #region Fields

        // The thread for processing delegates.
        private Thread delegateThread;

        // The queue for holding delegates.
        private Queue delegateQueue = new Queue();

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

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

        private ISite site = null;

        #endregion

        #region Events

        /// <summary>
        /// Occurs when an exception takes place as a result of a method 
        /// invocation.
        /// </summary>
        public event ExceptionEventHandler ExceptionOccurred;

        #endregion

        #region Construction

        /// <summary>
        /// Initializes a new instance of the DelegateQueue class.
        /// </summary>
        public DelegateQueue()
        {
            InitializeDelegateQueue();
        }

        public DelegateQueue(IContainer container)
        {
            ///
            /// Required for Windows.Forms Class Composition Designer support
            ///
            container.Add(this);

            InitializeDelegateQueue();
        }

        #endregion

        #region Methods

        /// <summary>
        /// Raises an event indicating that an exception has occurred.
        /// </summary>
        /// <param name="ex">
        /// The exception object representing information about the exception.
        /// </param>
        private void OnExceptionOccurred(Exception ex)
        {
            ExceptionEventHandler handler = ExceptionOccurred;

            if(handler != null)
            {
                handler(this, new ExceptionEventArgs(ex));
            }
        }

        private void InitializeDelegateQueue()
        {
            // Create thread for processing delegates.
            delegateThread = new Thread(new ThreadStart(DelegateProcedure));

            lock(lockObject)
            {
                delegateThread.Start();

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

        // Processes and invokes delegates.
        private void DelegateProcedure()
        {
            lock(lockObject)
            {
                // Signal the constructor that the thread is now running.
                Monitor.Pulse(lockObject);
            }

            Queue invokeQueue = new Queue();
            DelegateQueueAsyncResult result = null;

            // While the DelegateQueue has not been disposed.
            while(!disposed)
            {
                // Critical section.
                lock(lockObject)
                {
                    // If there are delegates waiting to be invoked.
                    if(delegateQueue.Count > 0)
                    {
                        // Enqueue all of the delegates currently in the queue 
                        // into the invocation queue. 
                        while(delegateQueue.Count > 0)
                        {           
                            invokeQueue.Enqueue(delegateQueue.Dequeue());
                        }
                    }
                    // Else there are no delegates waiting to be invoked.
                    else
                    {
                        // Wait for next delegate.
                        Monitor.Wait(lockObject);

                        // If the DelegateQueue has not been disposed.
                        if(!disposed)
                        {           
                            // Get the next delegate in the queue.
                            invokeQueue.Enqueue(delegateQueue.Dequeue());
                        }
                    }
                }

                // While the DelegateQueue has not been disposed and there are 
                // delegates to invoke.
                while(!disposed && invokeQueue.Count > 0)
                {          
                    try
                    {
                        // Get the next delegate.
                        result = (DelegateQueueAsyncResult)invokeQueue.Dequeue();

                        // Invoke the delegate.
                        result.Invoke();

                        // Signal that the delegate is done.
                        result.Signal();
                    }
                    catch(Exception ex)
                    {
                        // Get the exception that was thrown from the delegate.
                        result.Exception = ex.InnerException;

                        // Signal that the delegate is done.
                        result.Signal();

                        // If BeginInvoke was called.
                        if(!result.CompletedSynchronously)
                        {
                            OnExceptionOccurred(ex.InnerException);
                        }
                    }
                }
            }

            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 delegate of an DelegateQueue.
        /// </summary>
        public event System.EventHandler Disposed;

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

        #endregion

        #region ISynchronizeInvoke Members

        public IAsyncResult BeginInvoke(Delegate method, object[] args)
        {
            DelegateQueueAsyncResult result = new DelegateQueueAsyncResult(method, args, false);

            lock(lockObject)
            {
                delegateQueue.Enqueue(result);

                Monitor.Pulse(lockObject);
            }

            return result;
        }

        public object EndInvoke(IAsyncResult result)
        {
            result.AsyncWaitHandle.WaitOne();

            DelegateQueueAsyncResult r = (DelegateQueueAsyncResult)result;

            if(r.Exception != null)
            {
                throw r.Exception;
            }

            return r.ReturnValue;
        }

        public object Invoke(Delegate method, object[] args)
        {
            DelegateQueueAsyncResult result = new DelegateQueueAsyncResult(method, args, true);

            lock(lockObject)
            {
                delegateQueue.Enqueue(result);

                Monitor.Pulse(lockObject);
            }          

            return EndInvoke(result);
        }

        public bool InvokeRequired
        {
            get
            {
                return !(Thread.CurrentThread == delegateThread);
            }
        }        

        #endregion

        #region IDisposable Members

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

            if(disposed)
            {
                return;
            }

            #endregion

            lock(lockObject)
            {
                disposed = true;

                Monitor.Pulse(lockObject);
            }
        }

        #endregion                

        #region DelegateQueueAsyncResult Class

        /// <summary>
        /// Implements the IAsyncResult interface for the DelegateQueue class.
        /// </summary>
        private class DelegateQueueAsyncResult : IAsyncResult
        {
            // The delegate to be invoked.
            private Delegate method;

            // Args to be passed to the delegate.
            private object[] args;

            // An event which is set immediately after invoking the delegate to
            // indicated that the delegate has been invoked.
            private ManualResetEvent waitHandle = new ManualResetEvent(false);

            // Indicates whether or not Invoke was called.
            private volatile bool synchronously;

            // Indicates whether or not the delegate has been invoked.
            private volatile bool completed = false;

            // The object returned from the delegate.
            private object returnValue = null;            

            // Represents a possible exception thrown by invoking the method.
            private Exception exception = null;

            public DelegateQueueAsyncResult(Delegate method, object[] args, 
                bool synchronously)
            {
                this.method = method;
                this.args = args;
                this.synchronously = synchronously;
            }

            public void Invoke()
            {
                returnValue = method.DynamicInvoke(args);
                completed = true;
            }

            public void Signal()
            {
                waitHandle.Set();
            }

            public object ReturnValue
            {
                get
                {
                    return returnValue;
                }
            }

            public Exception Exception
            {
                get
                {
                    return exception;
                }
                set
                {
                    exception = value;
                }
            }

            #region IAsyncResult Members

            public object AsyncState
            {
                get
                {
                    return null;
                }
            }

            public bool CompletedSynchronously
            {
                get
                {
                    return synchronously;
                }
            }

            public WaitHandle AsyncWaitHandle
            {
                get
                {
                    return waitHandle;
                }
            }

            public bool IsCompleted
            {
                get
                {
                    return completed;
                }
            }

            #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