Declaring an Event


Declaring an Event

You declare an event in a class intended to act as an event source. An event source is usually a class that monitors its environment, and raises an event when something significant happens. In the automated factory, an event source could be a class that monitors the temperature of each machine. The temperature monitor class would raise a “machine overheating” event if it detects that a machine has exceeded its thermal radiation boundary (i.e. it has become too hot). An event maintains a list of methods to call when it is raised. These methods are sometimes referred to as subscribers. These methods should be prepared to handle the “machine overheating” event and take the necessary corrective action: shut the machines down.

You declare an event in a way similar to declaring a field. However, because events are intended be used with delegates, the type of an event must be a delegate, and you must prefix the declaration with the event keyword. For example, here's the StopMachineryDelegate delegate from the automated factory. I have relocated it to a new class called TemperatureMonitor, which provides an interface to the various electonic probes monitoring the temperature of the equipment (this is a more logical place for the event than the Controller class):

class TemperatureMonitor {     public delegate void StopMachineryDelegate();     ... }

You can define the MachineOverheating event, which will invoke the stopMachineryDelegate, like this:

class TemperatureMonitor {     public delegate void StopMachineryDelegate();     public event StopMachineryDelegate MachineOverheating;     ... }

The logic (not shown) in the TemperatureMonitor class automatically raises the MachineOverheating event as necessary. An event maintains its own internal collection of attached delegates, so there is no need to manually maintain your delegate variable.




Microsoft Visual C# 2005 Step by Step
Microsoft® Visual C#® 2005 Step by Step (Step By Step (Microsoft))
ISBN: B002CKYPPM
EAN: N/A
Year: 2005
Pages: 183
Authors: John Sharp

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net