如何:声明自定义事件以避免阻止 (Visual Basic)

在以下几种情况下,务必要确保一个事件处理程序不会阻止后续事件处理程序。 自定义事件允许事件异步调用其事件处理程序。

默认情况下,事件声明的备用存储字段是按顺序组合所有事件处理程序的多播委托。 这意味着,如果一个处理程序需要很长时间才能完成,那么它就会在完成之前阻止其他处理程序。 (行为良好的事件处理程序永远不应执行冗长或可能产生阻塞的操作。)

可以使用自定义事件异步执行事件处理程序,而不是使用 Visual Basic 提供的事件的默认实现。

示例

在此示例中,AddHandler 访问器将 Click 事件的每个处理程序的委托添加到存储在 EventHandlerList 字段中的 ArrayList

当代码引发 Click 事件时,RaiseEvent访问器使用 BeginInvoke 方法异步调用所有事件处理程序委托。 该方法调用工作线程上的每个处理程序并立即返回,因此处理程序不能相互阻止。

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)
            EventHandlerList.Add(value)
        End AddHandler
        RemoveHandler(ByVal value As EventHandler)
            EventHandlerList.Remove(value)
        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
            Next
        End RaiseEvent
    End Event
End Class

请参阅