// set the clock running it will raise an event for each new second public void Run() { for (;;) { // sleep 100 milliseconds Thread.Sleep(100); // get the current time System.DateTime dt = System.DateTime.Now; // if the second has changed notify the subscribers if (dt.Second != second) { // create the TimeInfoEventArgs object to pass to the subscriber TimeInfoEventArgs timeInformation = new TimeInfoEventArgs(dt.Hour, dt.Minute, dt.Second); // if anyone has subscribed, notify them if (SecondChanged != null) { SecondChanged(this, timeInformation); } } // update the state this.second = dt.Second; this.minute = dt.Minute; this.hour = dt.Hour; } }
// this method should write to a file // we write to the console to see the effect // this object keeps no state public void WriteLogEntry(object theClock, TimeInfoEventArgs ti) { Console.WriteLine("Logging to file: {0}:{1}:{2}", ti.hour.ToString(), ti.minute.ToString(), ti.second.ToString()); }
// the method that implements the delegated functionality public void TimeHasChanged(object theClock, TimeInfoEventArgs ti) { Console.WriteLine("Current Time: {0}:{1}:{2}", ti.hour.ToString(), ti.minute.ToString(), ti.second.ToString()); }
private void TheClock_SecondChange(object clock, TimeInfoEventArgs timeInformation) { throw new NotImplementedException(); }