Previous Page
Next Page

Using Events

In the following exercise, you will use events to simplify the program you completed in the first exercise. You will add an event field to the Ticker class and delete its Add and Remove methods. You will then modify the Clock.Start and Clock.Stop methods to subscribe to the event. You will also examine the Timer object, used by the Ticker class to obtain a pulse once each second.

Rework the digital clock application
  1. Return to Visual Studio 2005 displaying the Delegates project. In the Code and Text Editor window, display the Ticker.cs source file.

    This file contains the declaration of the Tick delegate type in the Ticker class:

    public delegate void Tick(int hh, int mm, int ss);
  2. Add a public event called tick of type Tick to the Ticker class.

    The Ticker class should now look like this:

    class Ticker
    {
        public delegate void Tick(int hh, int mm, int ss);
        public event Tick tick;
        ...
    }
  3. Comment out the following delegate variable tickers from end of Ticker class as it is now obsolete:

    // private Tick tickers;
  4. Comment out the Add and Remove methods from the Ticker class.

    The add and remove functionality is automatically provided by the += and –= operators of the event.

  5. In the Code and Text Editor window, locate the Ticker.Notify method. This method previously invoked an instance of the Tick delegate. Modify it so that it calls the tick event instead. Don't forget to check whether tick is null before calling the event.

    The Notify method should look like this:

    class Ticker
    {
        ...
        private void Notify(int hours, int minutes, int seconds)
        {
            if (this.tick != null)
            {
                this.tick(hours, minutes, seconds);
            }
        }
        ...
    }

    Notice that the Tick delegate specifies parameters, so the statement that raises the tick event must specify arguments for each of these parameters.

  6. Examine the ticking variable at the end of the class:

    private System.Timers.Timer ticking = new System.Timers.Timer();

    The Timer class is part of the .NET Framework. It can be programmed to repeatedly raise an event at a specified interval. Examine the constructor for the Ticker class:

    public Ticker()
    {
        this.ticking.Elapsed += new ElapsedEventHandler(this.OnTimedEvent);
        this.ticking.Interval = 1000; // 1 second
        this.Enabled = true;
    }

    The Timer class exposes the Elapsed event, which can be raised at regular intervals according to the Interval property. Setting Interval to 1000 causes the Elapsed event to be raised once a second (the value is specified in milliseconds). The timer starts when you set the Enabled property to true. The Timer class also provides the ElapsedEventHandler delegate, which specifies the signature of methods that can subscribe to the Elapsed event. The constructor creates an instance of this delegate referring to the OnTimedEvent method and subscribes to the Elapsed event. The OnTimedEvent method in the Ticker class extracts the information about the current time, which is passed in by using the ElapsedEventArgs parameter, and uses this information in turn to raise the tick event through the Notify method:

    private void OnTimedEvent(object source, ElapsedEventArgs args)
    {
        int hh = args.SignalTime.Hour;
        int mm = args.SignalTime.Minutes;
        int ss = args.SignalTime.Seconds;
        Notify(hh, mm, ss);
    }
    NOTE
    For more information about the Timer class and the ElapsedEventArgs class, see the Microsoft Visual Studio 2005 Documentation provided with Visual Studio 2005.
  7. In the Code and Text Editor window, display the Clock.cs source file.

  8. Change the Clock.Start method so that the delegate is attached to the tick event of the pulsed field by using the += operator.

    The Clock.Start method should look like this:

    public void Start()
    {
        pulsed.tick += this.RefreshTime;
    }
  9. In the Code and Text Editor window, change the Clock.Stop method so that the delegate is detached from the tick event of the pulsed field by using the –= operator.

    The Clock.Stop method should look like this:

    public void Stop()
    {
        pulsed.tick -= this.RefreshTime;
    }
  10. On the Debug menu, click Start Without Debugging. The project builds and runs.

  11. Click Start.

    The digital clock form displays the correct time and updates the display every second.

  12. Click the Stop button to verify that the clock stops.

  13. Close the form.


Previous Page
Next Page