Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 交叉线程无效_Vb.net - Fatal编程技术网

Vb.net 交叉线程无效

Vb.net 交叉线程无效,vb.net,Vb.net,我试图在VB.NET中进行串行通信,但出现以下错误: 跨线程操作无效:控件“TextBox1”是从创建它的线程以外的线程访问的 代码如下: Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles sp.DataReceived Dim str As String = sp.ReadExisting(

我试图在VB.NET中进行串行通信,但出现以下错误:

跨线程操作无效:控件“TextBox1”是从创建它的线程以外的线程访问的

代码如下:

Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles sp.DataReceived
    Dim str As String = sp.ReadExisting()
    TextBox1.Text = str
End Sub

在完成线程调用新方法后使用全局变量

Dim xStr as string=string.Empty

Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e 
As System.IO.Ports.SerialDataReceivedEventArgs) Handles sp.DataReceived
    xStr=  sp.ReadExisting()
    Me.Invoke(New MethodInvoker(AddressOf Display))
End Sub

Private Sub Display ()
     TextBox1.Text=xStr
end sub

DataReceived
事件位于与UI线程不同的线程上,因此禁止访问控件。您可以在Invoke方法中使用lambda子函数,这样您就可以直接访问控件,因为我们回到了这里的UI线程上

Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles sp.DataReceived
  Me.Invoke(Sub()
              Textbox1.Text = sp.ReadExisting()
            End Sub)
End Sub

非常感谢你!你不知道你帮了我多少忙!