Redder
Redder

Reputation: 146

VB.NET Invoke Method

I have this method in my code:

Private Sub Display()
        Received.AppendText(" - " & RXArray)
End Sub

Whats the difference between this 2 calls:

Me.Invoke(New MethodInvoker(AddressOf Display))

AND

Display()

I know that is something about threading, but I'm not sure.

Thanks in advance

Upvotes: 8

Views: 44270

Answers (3)

Levis
Levis

Reputation: 39

For future readers, you could also update your UI object by doing the following

Private Sub Display()
    If Me.InvokeRequired Then
        Me.Invoke(Sub()  Received.AppendText(" - " & RXArray))
        Return
    End IF

End Sub

Upvotes: 1

Caglayan ALTINCI
Caglayan ALTINCI

Reputation: 49

Adding parameters to the other answer:

Private Sub Display(ByVal strParam As String)
    If Me.InvokeRequired Then
        Me.Invoke(Sub() Display(strParam))
        Return
    End IF
    Received.AppendText(" - " & RXArray)
End Sub

Upvotes: 5

jor
jor

Reputation: 2157

Use the Invoke way when you're working in different threads. For example if the caller is not in the same thread as the GUI.

If the caller doesn't need to wait for the result of the method, you could even use BeginInvoke:

GuiObject.BeginInvoke(New MethodInvoker(AddressOf Display))

Or shorter:

GuiObject.BeginInvoke(Sub() Display)

For more ease of writing you could move the invoking into the Display function:

Private Sub Display()
    If Me.InvokeRequired Then
        Me.Invoke(Sub() Display)
        Return
    End IF
    Received.AppendText(" - " & RXArray)
End Sub

That way the caller doesn't have to know whether he is in the same thread or not.

Upvotes: 12

Related Questions