Information Technology Reference
In-Depth Information
Raising an Event
The event member itself just holds the event handlers that need to be invoked. Nothing hap-
pens with them unless the event is raised. You need to make sure there is code to do just that,
at the appropriate times.
For example, the following code raises event Elapsed . Notice the following about the code:
Before raising the event, it is compared to null , to see whether it contains any event han-
dlers. If the event is null , it is empty.
￿
￿
Raising the event itself is like invoking a function.
-
Use the name of the event, followed by the parameter list enclosed in parentheses.
-
The parameter list must match the delegate type of the event.
if (Elapsed != null) // Make sure there are methods to execute.
Elapsed( obj, e ); // Raise the event.
Event name Parameter list
Putting together the event declaration and the code to raise the event gives the following
class declaration for the publisher. The code contains two members: the event, and a method
called OnOneSecond , which raises the event.
public class MyTimerClass
{
public event EventHandler Elapsed; // Declare the event.
private void OnOneSecond(object obj, EventArgs e)
{
if (Elapsed != null) // Make sure there are methods to execute.
Elapsed(obj, e );
}
Raise the event.
// The following code makes sure that method OnOneSecond is called every
// 1,000 milliseconds.
...
}
For now, I'll let method OnOneSecond be somehow, mysteriously, called once every second.
Later in the chapter I'll show you how to make this happen. But for now, remember these
important points:
￿
The class has an event.
￿
The class has the code to raise the event.
Search WWH ::




Custom Search