VB.NET 调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17717709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 17:00:29  来源:igfitidea点击:

VB.NET Invoke Method

vb.netmultithreadingdelegates

提问by Redder

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

提前致谢

回答by jor

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

Invoke在不同线程中工作时使用该方式。例如,如果调用者与 GUI 不在同一个线程中。

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

如果调用者不需要等待方法的结果,您甚至可以使用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 Displayfunction:

为了更易于编写,您可以将调用移动到Display函数中:

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.

这样调用者就不必知道他是否在同一个线程中。

回答by Caglayan ALTINCI

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

回答by Levis

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

对于未来的读者,您还可以通过执行以下操作来更新您的 UI 对象

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

End Sub