次の方法で共有


方法: ブロックを回避するためにカスタム イベントを宣言する (Visual Basic)

1 つのイベント ハンドラーが後続のイベント ハンドラーをブロックしないことが重要な状況がいくつかあります。 カスタム イベントを使用すると、イベントはイベント ハンドラーを非同期的に呼び出します。

既定では、イベント宣言のバッキング ストア フィールドは、すべてのイベント ハンドラーを順次結合するマルチキャスト デリゲートです。 つまり、1 つのハンドラーの完了に時間がかかる場合は、完了するまで他のハンドラーがブロックされます。 (適切に動作するイベント ハンドラーは、長い操作やブロックする可能性のある操作を実行しないでください)。

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

こちらも参照ください