11.6. Custom Events

Both C# and VB.NET can declare custom events that determine what happens when someone subscribes or unsubscribes from an event, and how the subscribers list is stored. Note that the VB.NET example is more verbose, but it enables you to control how the event is actually raised. In this case, each handler is called asynchronously for concurrent access. The RaiseEvent waits for all events to be fully raised before resuming:

C#

List<EventHandler> EventHandlerList = new List<EventHandler>();

public event EventHandler Click{
    add{EventHandlerList.Add(value);}
    remove{EventHandlerList.Remove(value);}
}

VB.NET

Private EventHandlerList As New ArrayList

Public Custom Event Click As EventHandler
    AddHandler(ByVal value As EventHandler)
        EventHandlerList.Add(value)
    End AddHandler
    RemoveHandler(ByVal value As EventHandler)
        EventHandlerList.Remove(value)
    End RemoveHandler
    RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
        Dim results As New List(Of IAsyncResult)
        For Each handler As EventHandler In EventHandlerList
            If handler IsNot Nothing Then
                results.Add(handler.BeginInvoke(sender, e, Nothing, Nothing))
            End If
        Next
        While results.Find(AddressOf IsFinished) IsNot Nothing
            Threading.Thread.Sleep(250)
        End While
    End RaiseEvent
End Event
Private Function IsFinished(ByVal async As IAsyncResult) As Boolean
    Return async.IsCompleted
End Function

Get Professional Visual Studio® 2008 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.