共用方式為


HOW TO:宣告自訂事件以避免封鎖 (Visual Basic)

如果其中一個事件處理常式未封鎖後續事件處理常式是十分重要的,則會有數種情況。 自訂事件允許事件非同步呼叫它的事件處理常式。

事件宣告的支援存放區欄位預設是連續結合所有事件處理常式的多點傳送委派 (Delegate)。 這表示如果某個處理常式需要較長的時間才能完成,則它會封鎖另一個處理常式,直到完成為止 (行為正確的事件處理常式絕不會長期執行或封鎖作業)。

不使用 Visual Basic 所提供之事件的預設實作,而是使用自訂事件非同步地執行事件處理常式。

範例

在這個範例中,AddHandler 存取子 (Accessor) 會將 Click 事件之每個處理常式的委派加入至儲存在 EventHandlerList 欄位中的 ArrayList

程式碼引發 Click 事件時,RaiseEvent 存取子會使用 BeginInvoke 方法非同步叫用 (Invoke) 所有事件處理常式委派。 該方法會叫用背景工作執行緒 (Worker Thread) 上的每個處理常式並立即傳回,因此,處理常式無法互相封鎖。

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

請參閱

工作

HOW TO:宣告自訂事件以節省記憶體 (Visual Basic)

參考

ArrayList

BeginInvoke

其他資源

事件 (Visual Basic)