Search code examples
vb.netsubroutineaddhandler

Raising an event through subroutine


I'm trying to raise an event through subroutine to notify some of my program's observers that the animated transition has been completed. But it tells me it cannot be called directly and I need to use a RaiseEvent. I tried adding handlers, and it still doesn't work. What should I do?

Utility.raiseEventTest(Me.TransitionCompletedEvent, Me, New Transition.Args())

https://prntscr.com/fiholb

 Public Shared Sub raiseEventTest(Of T As System.EventArgs)(theEvent As EventHandler(Of T), sender As Object, args As T)
        If theEvent Is Nothing Then
            Return
        End If
        '
        For Each handler As EventHandler(Of T) In theEvent.GetInvocationList()
            Try
                Dim target As ISynchronizeInvoke = TryCast(handler.Target, ISynchronizeInvoke)
                If target Is Nothing OrElse target.InvokeRequired = False Then
                    handler(sender, args)
                Else
                    target.BeginInvoke(handler, New Object() {sender, args})
                End If
            Catch generatedExceptionName As Exception
            End Try
        Next
    End Sub

Solution

  • Just use RaiseEvent as suggested, there is no need for you to use that type of code...

    Change:

    Utility.raiseEventTest(Me.TransitionCompletedEvent, Me, New Transition.Args())
    

    To:

    RaiseEvent TransitionCompleted(Me, New Transition.Args())
    

    All subscribers will be notified and receive the event.