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

在某些情况下,一个事件处理程序不阻止后续事件处理程序非常重要。 自定义事件允许事件异步调用其事件处理程序。

默认情况下,事件声明的备用存储字段是按顺序组合所有事件处理程序的多播委托。 这意味着,如果一个处理程序需要很长时间才能完成,它将阻止其他处理程序,直到它完成。 行为良好的事件处理程序绝不应执行冗长或可能导致阻塞的操作。

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

示例:

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

当代码引发 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

另请参阅