Creating and Raising Events

There is not much functionality you can build using the .NET languages without events. Events enable one piece of code to notify another bit of code that something has just happened. Code that raises events is said to publish an event, and code that receives the event notice is said to subscribe to events. A simple example is when you write a user interface for the Web or Windows. In these cases, you are consistently adding code that subscribes to events published by the UI, such as a user clicking a button control. Of course, an event may have more than a single subscriber, and subscribers may subscribe to multiple events.

Define an Event

When you define an event you need to determine whether you need to pass custom data to the subscribers. This custom data is referred to as event arguments (or args). If you do not need to pass custom data, you simply declare the event using the keyword event and the existing delegate EventHandler. For example, if you were to define a simple event that you would raise when an employee class is updated, you might define that event as follows.

C#

public event EventHandler EmployeeUpdatedEvent;

VB

Public Event EmployeeUpdatedEvent As EventHandler

By declaring the event, you have effectively published it. Subscribers who have a reference to your class can then set up a subscription to your event. You then need to raise the event in the same class where you published it. This notifies the subscribers that the event has fired.

It is slightly more complicated to define events where you need to pass custom data. In this case, you must first create a custom class to maintain your event data. This class must inherit from the EventArgs base class. For example, you might create a custom event arguments class to contain the employee ID for the employee-updated event. In this case, your custom class contains a property to hold the Id value and a constructor for passing in this value, as in the following code.

C#

public class EmployeeUpdatedEventArgs : EventArgs
{
  public EmployeeUpdatedEventArgs(string id)
  {
    _id= id;
  }

  private string _id;
  public string EmployeeId
  {
    get { return _id; }
  }
}

VB

Public Class EmployeeUpdatedEventArgs
  Inherits EventArgs

  Public Sub New(ByVal id As String)
    _id= id
  End Sub

  Private _id As String
  Public ReadOnly Property EmployeeId() As String
    Get
      Return _id
    End Get
  End Property

End Class

When you use a custom event argument, you need to declare your event to use the custom event argument class. You can do so using the version of the EventHandler class that is defined as generic. In this case, you indicate the class that contains the argument as part of the generic definition of EventHandler. This class also automatically contains the sender argument (typically a copy of the object publishing the event). The following shows an example of defining this custom event handler.

C#

public event EventHandler<EmployeeUpdatedEventArgs> EmployeeUpdatedCustomEvent;

VB

Public Event EmployeeUpdatedCustomEvent As _
  EventHandler(Of EmployeeUpdatedEventArgs)

Raise an Event

You raise the event in the same class where the event is defined. An event is raised as the result of some action. In the case of the example, the action in the employee class has been updated. To raise the event, you simply call it in the right spot and pass the appropriate parameters. In the case of the employee-updated custom event, you pass an instance of the employee class as the sender and then the employee Id as part of an instance of the EmployeeUpdatedEventArgs, as shown here.

C#

public void UpdateEmployee()
{
  //do work to update employee ...

  //raise event to notify subscribers of the update
  EmployeeUpdatedCustomEvent(this, new EmployeeUpdatedEventArgs(this.Id));
}

VB

Public Sub UpdateEmployee()
  'do work to update employee ...

  'raise event to notify subscribers of update
  RaiseEvent EmployeeUpdatedCustomEvent(Me, _
    New EmployeeUpdatedEventArgs(Me.Id))
End Sub

Subscribe to and Handle an Event

The final step is to actually listen for (or subscribe to) the event. Here, you need to do two things. First, you must write a method that mimics the signature of the event. The content of this method is yours to write. It is called when the event fires. The following shows an example of a method (inside a class that subscribes to the employee class) that is called when the event fires. Notice how this method uses the custom event type and must therefore match that signature.

C#

private void OnEmployeeUpdate(object sender, EmployeeUpdatedEventArgs e)
{
  //do something in response to employee update
  string empId = e.EmployeeId;
}

VB

Private Sub OnEmployeeUpdate(ByVal sender As Object, _
  ByVal e As EmployeeUpdatedEventArgs)

  Dim empId As String = e.EmployeeId
  Console.WriteLine("Event Fired: id=" & empId)
End Sub

Second, you must register your event handler with the actual event. You do this by adding a pointer to the event using the += (C#) or AddHandler (VB) syntax. You typically add your handlers inside the subscribing class’s constructor or initialization code. The following shows code to connect the OnEmployeeUpdate handler to the EmployeeUpdatedCustomEvent event.

C#

Employee _emp = new Employee();
_emp.EmployeeUpdatedCustomEvent += this.OnEmployeeUpdate;

VB

AddHandler _emp.EmployeeUpdatedCustomEvent, AddressOf OnEmployeeUpdate

When the code is run, you undoubtedly access features of the class that fire the event (in this case, Employee.UpdateEmployee). When you hit a method that triggers the event, your subscribing code is called accordingly. When you don’t need to listen to the event, you must remember to unsubscribe your handler from the event. If you forget to do so, the garbage collector might not be able to free the memory used by the listener object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset