SDK Event Handling in C# using delegates


Event-Handling in .NET

In Microsoft .NET, events are first-class entities built into the framework. Any object can expose events in much the same way that it can expose properties or methods. A client application indicates that it wants to handle an event by attaching a delegate, which is essentially a typed reference to an event-handler method.

The .NET model imposes some of the same restrictions on the design of the StarTeam event-handling APIs as the COM model does. The object exposing the event implies the scope of interest. When a delegate is attached to an event, there is no syntactic mechanism that allows the client application to provide parameters to refine the scope.  

For this reason, the event-handling APIs in the StarTeam SDK for .NET use EventSource objects similar to those used in the COM APIs. A client application creates an EventSource object using a factory method on the relevant parent class, and attaches its event-handlers to events exposed on the EventSource. Each EventSource defines a delegate type that specifies the calling conventions of the corresponding event handlers.

For example, an application might handle OnItemAdded events for items of type "File" as follows:

void ListenForFilesAdded(View view) { 
    Server s = view.Server; 
    Type type = s.Types.FILE; 

    // Create an event source via a factory method on the view.
    // The view and item type define the scope of interest.
    ItemEventSource source = view.NewItemEventSource(type); 

    // ItemEventSource exposes the OnItemAdded event (and others).
    // Attach an application event handler.
    // ItemEventSource.Handler is a delegate type.
    source.OnItemAdded  = new ItemEventSource.Handler(OnFileAdded); 

// The event handler.
private void OnFileAdded(ItemEventSource source, ItemEventArgs args) { 
    File file = (File)args.NewItem; 
    Console.WriteLine("File Added: "   file.Name); 

When writing an event-handler in .NET, the same basic principles apply as in Java and COM. Event-handlers use the same object model as the rest of the SDK. There are no significant constraints that limit what can be done within the event-handler itself.



How To-Best Practice
Comment List