Events
[private | public] event identifier ([param {, param}])
An event is commonly referred to as callback mechanism which can notify a program when something needs to be done or if something has happened. A subroutine that processes an event is called an event handler. An event handler is usually invoked or raised by another module. A good example of an event can be found in the main device system file and is called OnStartup(). This enables you to execute code statements before any module initialization code or main program code is executed. For example,
' event handler... Sub OnStartup() Handles PIC.OnStartup ' initialisaton code in here End Sub ' main program entry point... Sub Main() End Sub
The OnStartup() event handler in this example could be used to configure an internal oscillator before any other code statements are executed. Event handlers must be subroutines, they cannot be functions. In addition, you must identify or tag the subroutine as an event handler by using the handles keyword, followed by the name of the handler as declared in the module. In the previous example, the device module name is "PIC" which declares a public event called "OnStartup".
Declaring An Event
To declare an event, you use the event keyword. For example,
Public Event OnStartup()
Events can be declared with parameters. For example,
Public Event OnFound(ID As Byte, ByRef Abort As Boolean)
Raising and Event
To raise an event, you use the raiseevent keyword. For example,
RaiseEvent OnFound(10, AbortSearch)
You can test an event against nothing to see if an event handler has been assigned. For example,
' this code is only linked in at compile time if an event handler has ' been assigned to OnData... If OnData <> Nothing Then Dim Accept As Boolean = True RaiseEvent OnData(ByteRead, Accept) ' if the accept flag is still true, buffer the data If Accept Then ' process data... End If ' this code is only linked in at compile time if no event ' handler has been assigned to OnData... Else ' process data... End If
In this example, if no event handler has been assigned to OnData() then all the code statements between if…else is removed by the compiler.
Events and Interrupts
You can raise an event from within an interrupt handler but care must be taken with respect to context saving (see the section on interrupts for more information on context saving). In effect, your event handler is plugging code directly into your interrupt routine. The same context save rules apply to your event handler as if the code had been written directly inside the interrupt handler itself.


