Net事件安全调用模式

来源:互联网 发布:java接口api生成工具 编辑:程序博客网 时间:2024/06/13 02:45

 Public Class MyPublisher

        Public Delegate Sub GenericEventHandler(Of T, U)(ByVal t As T, ByVal u As U)
        Public Delegate Sub GenericEventHandler(Of T)(ByVal t As T)

        Private deles As New List(Of GenericEventHandler(Of Integer))

        Public Event SyncNumberChanged As GenericEventHandler(Of Integer)

        Public Custom Event AsyncNumberChanged As GenericEventHandler(Of Integer)
            AddHandler(ByVal value As GenericEventHandler(Of Integer))
                deles.Add(value)
            End AddHandler

            RemoveHandler(ByVal value As GenericEventHandler(Of Integer))
                deles.Remove(value)
            End RemoveHandler

            RaiseEvent(ByVal t As Integer)
                Dim synchronizer As System.ComponentModel.ISynchronizeInvoke
                For Each dele As GenericEventHandler(Of Integer) In deles
                    synchronizer = TryCast(dele.Target, System.ComponentModel.ISynchronizeInvoke)
                    If synchronizer IsNot Nothing Then
                        If synchronizer.InvokeRequired = True Then
                            synchronizer.Invoke(dele, New Object() {t})
                            Return
                        End If
                    End If
                    dele.DynamicInvoke(t)
                Next
            End RaiseEvent
        End Event

        Public Sub AsyncFireEvent(ByVal int As Integer)
            RaiseEvent AsyncNumberChanged(int)
        End Sub

        Public Sub SyncFireEvent(ByVal int As Integer)

        End Sub

    End Class