Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 640
Redder Avatar asked Jul 18 '13 07:07

Redder


People also ask

What is the purpose of Invoke method in VB net?

The Invoke method searches up the control's parent chain until it finds a control or form that has a window handle if the current control's underlying window handle does not exist yet. If no appropriate handle can be found, the Invoke method will throw an exception.

How do I invoke in Visual Basic?

Invoke the Developer Command Prompt for Visual Studio. At the command line, type vbc.exe sourceFileName and then press ENTER. For example, if you stored your source code in a directory called SourceFiles , you would open the Command Prompt and type cd SourceFiles to change to that directory.

Why invoke is used?

Invoke is used of putting into effect or calling upon such things as laws, authority, or privilege (“the principal invoked a rule forbidding students from asking questions”). Evoke is primarily used in the sense “to call forth or up” and is often found in connection with such things as memories, emotions, or sympathy.


1 Answers

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.

like image 166
jor Avatar answered Nov 15 '22 07:11

jor