How to: Declare Custom Events To Avoid Blocking (Visual Basic)


Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

There are several circumstances when it is important that one event handler not block subsequent event handlers. Custom events allow the event to call its event handlers asynchronously.

By default, the backing-store field for an event declaration is a multicast delegate that serially combines all the event handlers. This means that if one handler takes a long time to complete, it blocks the other handlers until it completes. (Well-behaved event handlers should never perform lengthy or potentially blocking operations.)

Instead of using the default implementation of events that Visual Basic provides, you can use a custom event to execute the event handlers asynchronously.

In this example, the AddHandler accessor adds the delegate for each handler of the Click event to an ArrayList stored in the EventHandlerList field.

When code raises the Click event, the RaiseEvent accessor invokes all the event handler delegates asynchronously using the BeginInvoke method. That method invokes each handler on a worker thread and returns immediately, so handlers cannot block one another.

    Public NotInheritable Class ReliabilityOptimizedControl
        'Defines a list for storing the delegates
        Private EventHandlerList As New ArrayList

        'Defines the Click event using the custom event syntax.
        'The RaiseEvent always invokes the delegates asynchronously
        Public Custom Event Click As EventHandler
            AddHandler(ByVal value As EventHandler)
            End AddHandler
            RemoveHandler(ByVal value As EventHandler)
            End RemoveHandler
            RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
                For Each handler As EventHandler In EventHandlerList
                    If handler IsNot Nothing Then
                        handler.BeginInvoke(sender, e, Nothing, Nothing)
                    End If
            End RaiseEvent
        End Event
    End Class

How to: Declare Custom Events To Conserve Memory