Instantiate a static class at application startup (c#)

Merrion

Junior Contributor
Joined
Sep 29, 2001
Messages
265
Location
Dublin, Ireland
Hi

I have a static class that acts as a "hearbeat" to allow external listeners to tell if the application is running healthily :-

Code:
       private static HeartbeatListenerCollection _listeners = new HeartbeatListenerCollection();

        /// <summary>
        /// Sends a heartbeat to any heartbeat monitors
        /// to indicate that the application is running
        /// </summary>
        public static void Beat()
        {
            // make each heartbeat listener beat 
            foreach (HeartbeatMonitorBase  _listener in Listeners)
            {
                _listener.Beat();
            }
        }

        /// <summary>
        /// Starts the heartbeat with a default frequency
        /// </summary>
        static Heartbeat()
        {
            // Fire up a thread to invoke hearbeat events 
            // perdiodically...
            TimerCallback timerDelegate =
            new TimerCallback(Heartbeat.Beat);

            AutoResetEvent autoEvent = new AutoResetEvent(false);

            System.Threading.Timer heartbeatTimer =
                new System.Threading.Timer(timerDelegate, autoEvent, 0,1000);
            

        }


        /// <summary>
        /// The listeners attached to the heartbeat
        /// </summary>
        /// <remarks >
        /// These should not be triggered directly but rather the 
        /// Heartbeat.Beat() method should be called
        /// </remarks>
        public  static HeartbeatListenerCollection Listeners
        {
            get { return Heartbeat._listeners; }
        }

    }

However the static class is only instantiated the first time it is referred to (effectively the heart only starts beating if we start listening to it). Can anyone think of aclever way to instantiate this class at application startup automatically?
 
If a tree falls in the woods and nobody is around to hear it...

Perhaps a silly question, but if there are no listeners, why does it matter whether the heartbeat thread is running?

Assuming this is your application, can you not just call Beat or an initialization method at application start?
 
if there are no listeners, why does it matter whether the heartbeat thread is running?
Ah - there is a supposed to be a default listener. Kind of like the way "Trace" works.

Assuming this is your application
I'd like to attach it to existing coded applications
 
Back
Top