vb.netmultithreadingdelegates

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


Solution

  • 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.