Information Technology Reference
In-Depth Information
This code produces the following output:
Class A Message: Message from OnOneSecond
Class A Message: Message from OnOneSecond
Class A Message: Message from OnOneSecond
The MyTimerClass Code
Now that you've seen all five areas of code that need to be implemented to use an event, I can
show you the full MyTimerClass class that I have been using.
Most things about the class have been pretty clear—it has an event called Elapsed that can
be subscribed to, and a method called OnOneSecond that is called every second and raises the
event. The one question remaining about it is, what causes OnOneSecond to be called every
second?
The answer is that OnOneSecond is, itself, an event handler that is subscribed to an event in
a class called Timer , in the System.Timers namespace. The event in Timer is raised every 1,000
milliseconds and calls event handler OnOneSecond , which in turn raises event Elapsed in class
MyTimerClass . Figure 16-5 shows the structure of the code.
Figure 16-5. The code structure of MyTimerClass
The Timer class is a useful tool, so I'll mention a little more about it. First, it has a public
event called Elapsed . If that sounds familiar, it's because I named the event in MyTimerClass
after it. The names have no other connection than that. I could have named the event anything.
One of the properties of Timer is Interval , which is of type double , and specifies the num-
ber of milliseconds between raising the event. The other property I use is Enabled , which is of
type bool , and starts and stops the timer.
Search WWH ::




Custom Search