Information Technology Reference
In-Depth Information
Subscribing to an Event
To add an event handler to an event, the handler must have the same return type and signature
as the event's delegate.
Use the
+=
operator to add an event handler to an event, as shown in the following code.
The method can be either an instance method or a static method.
For example, the following code adds three methods to event
Elapsed
.
Class
Instance method
↓
↓
mc.Elapsed += ca.TimerHandlerA; // Method reference form
mc.Elapsed +=
ClassB.TimerHandlerB
; // Method reference form
↑
↑
Event member
Static method
mc.Elapsed += new EventHandler(cc.TimerHandlerC); // Delegate form
The following program uses the
MyTimerClass
class declared in the previous section. The
code performs the following:
It registers two event handlers from two different class instances.
After registering the event handlers, it sleeps for 2 seconds. During that time, the timer
class raises the event two times, and both event handlers are executed each time.