C#, ActiveObject (Runnable)

This is a post after a long hibernation. Often in our product we need worker threads performing a given action when signaled. Thread pool threads (modified ThreadPool class, not the Microsoft supplied one) may not be ideal for this as these are rather foreground, "active" operations in contrast to the background callback model ThreadPool usually projects. Observing the repeating nature of such threads, I decided to patternize this model having  some resemblance to the IRunnable interface of Java. I've chosen a simpler implementation for ActiveObjects. More complex implementations can be found over net - for example.

     ///

    /// Active Object (runnable) interface     ///     public interface IActiveObject     {         ///         /// Initialize an active object         ///         ///         ///         void Initialize(string name, Action action);

        ///

        /// Signal the active object to perform its loop action.         ///         ///         /// Application may call this after some simple or complex condition evaluation         ///         void Signal;

        ///

        /// Signals to shotdown this active object         ///         void Shutdown;     }

Abiding by good design principles, the interface enforces a "shutdown" / "soft abort" mechanism for the active objects. A KISS implementation of the above interface is given beneath,

///

    /// Implements a simple active object pattern implementation     ///     ///     /// Although there exists a vast number of active objects patterns (in Java they are just "runnable")     /// scattered, one of the best I found is located at http://blog.gurock.com/wp-content/uploads/2008/01/activeobjects.pdf     ///     public class ActiveObject: IActiveObject     {         ///         /// Name of this active object         ///         private string m_Name;                 ///         /// Underlying active thread         ///         private Thread m_ActiveThreadContext;

        ///

        /// Abstracted action that the active thread executes         ///         private Action m_ActiveAction;

        ///

        /// Primary signal object for this active thread.         /// See the Signal method for more.         ///         private AutoResetEvent m_SignalObject;

        ///

        /// Signal object for shutting down this active object         ///         private ManualResetEvent m_ShutdownEvent;

        ///

        /// Interal array of signal objects combining primary signal object and         /// shutdown signal object         ///         private WaitHandle[] m_SignalObjects;                 public ActiveObject         {         }

        public void Initialize(string name, Action action)         {             m_Name = name;             m_ActiveAction = action;             m_SignalObject = new AutoResetEvent(false);             m_ShutdownEvent = new ManualResetEvent(false);             m_SignalObjects = new WaitHandle[]                                 {                                     m_ShutdownEvent,                                     m_SignalObject                                 };

            m_ActiveThreadContext = new Thread(Run);             m_ActiveThreadContext.Name = string.Concat("ActiveObject.", m_Name);             m_ActiveThreadContext.Start;         }                 private bool Guard         {             int index = WaitHandle.WaitAny(m_SignalObjects);             return index == 0? false: true;         }                 ///

        /// Signal the active object to perform its loop action.         ///         ///         /// Application may call this after some simple of complex condition evaluation         ///         public void Signal         {             m_SignalObject.Set;         }                 ///         /// Signals to shotdown this active object         ///         public void Shutdown         {             m_ShutdownEvent.Set;                         if (m_ActiveThreadContext!= null)             {                 m_ActiveThreadContext.Join;             }                         m_ActiveThreadContext = null;         }                 ///         /// Core run method of this active thread         ///         private void Run         {             try             {                 while (Guard)                 {                     try                     {                         m_ActiveAction;                     }                     catch (Exception ex)                     {                         Logger.Write(new LogData(string.Format("ActiveObject::Run - Name: {0}, Loop Error: {1}",                                                                m_Name,                                                                ex.Message),                                              Component.WebAstra,                                              LogLevel.Error));                     }                 }             }             catch(Exception ex)             {                 Logger.Write(new LogData(string.Format("ActiveObject::Run - Name: {0}, Error: {1}",                                                        m_Name,                                                        ex.Message),                                      Component.WebAstra,                                      LogLevel.Error));             }             finally             {                 m_SignalObject.Close;                 m_ShutdownEvent.Close;                                 m_SignalObject = null;                 m_ShutdownEvent = null;             }         }     }

The module/functional entity that requires to be "active" can compose the ActiveObject within it and provide an appropriate Action delegate.

public class EntityAgent {     private IActiveObject m_PickupActiveObject;        public EntityAgent(...)     {         m_PickupActiveObject = new ActiveObject;     }

    public void Initialize     {         m_PickupActiveObject.Initialize("Pickup", TryPickupInternalAsync);     }

    public void SomeComplexConditionEvaluation     {        //...

       m_PickupActiveObject.Signal;     }     private void TryPickupInternalAsync     {          //Your loop action here     } }

Patterns may not be strict GoF-patterns but most of the times are learned or devised on the fly by designers, developers and architects. I'll keep this post short as Deewali celebration is going on frenzy outside. Happy Deewali to all and keep hacking.

This article is part of the GWB Archives. Original Author: dbose

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.