2008-01-24

How to raise an event

It is very simple to raise events in dotnet/C#.
But there is a caveat one should be aware of; especially since it probably will show itself intermittently and be hard to track down. It is when someone finishes his listening for the event between the does-someone-listen-for-the-event and the very firing.
The good news is that it is easily solved by a temporary variable like so:

internal event NavigateDelegate OnNavigate;

internal delegate void NavigateDelegate( NavigateTypes navigateType );

private void Raise_OnNavigate(NavigateTypes navigateType)
{
    NavigateDelegate tempEvent = OnNavigate;
    if (null != tempEvent)
    {
        OnNavigate(navigateType);
    }
}


If the above is hard to remember there is a snippet
    invoke
to use.  Just write it at a line and press Tab.

1 comment:

Unknown said...

In Addition, a composite application which is composed by several modules connected to a main frame (aka CAB - http://www.cabpedia.com ) brought by patterns & practices group at Microsoft, has a really cool concept named the Event Broker. This concept exposes an event through the application depending the scope of the command that raises event. Also it has the event subscribers to that event that identify it by the string in which the event has been fired.
Something like:

[EventPublication("MyEvent", EventScope.Global)]
//...event definition and event raise
//event scope has also the option to fire through the local workitem

and somewhere else trough the application:

[EventSubscription("MyEvent", EventScope.Global )]
//Method that handles the event.
//has also a scope set