July 2008
Intermediate to advanced
1026 pages
27h 59m
English
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
Read now
Unlock full access