如何使用串行连接vb.net进行多线程处理

时间:2016-10-07 11:26:31

标签: vb.net multithreading serial-port

我有一个到远程机器的串行连接,我正在使用vb.net开发一个窗体,以收集一些信息。

所以你可以在下面的代码中看到我等到我收到完整的字符串(长度为4,#作为分隔符)来更改一些文本框文本。

Dim ReceivedTextSeries As String = vbNullString

Private Sub ReceivedText(ByVal [text] As String)

    If TextBoxConsola.InvokeRequired Then
        Dim x As New SetTextCallBlack(AddressOf ReceivedText)
        Me.Invoke(x, New Object() {(text)})
        ReceivedTextSeries &= [text]
        JustTesting()
    Else
        TextBoxConsolaReceived.Text &= [text]
        ReceivedTextSeries &= [text]
        JustTesting()
    End If

End Sub
Sub JustTesting()
    Dim Series() As String = ReceivedTextSeries.Split("#")
    If Series.Length = 4 Then
        TextBox1.Text = Series(0)
        TextBox2.Text = Series(2)
    End If
End Sub

但是我收到一条错误,说不允许多线程.. The operation between threads is not valid: Control 'TextBox1' accessed from a thread other than the thread where it was created.

我现在如何管理这个?我试图添加事件处理程序以避免这种情况,但没有成功..

1 个答案:

答案 0 :(得分:1)

因此,您可以创建一个调用文本框的快速子。你已经在以前的方法中这样做了。这使它可以重复使用。

Private Sub UpdateTextBox(Text As String, TextBox As TextBox)
    If TextBox.InvokeRequired Then
        TextBox.Invoke(DirectCast(Sub() UpdateTextBox(Text, TextBox), Action))
        Exit Sub
    End If
    TextBox.Text = Text
End Sub

然后可以使用

调用写入文本框的所有调用
UpdateTextBox("My Text", TextBox1)

因此,您可以使用代码

Sub JustTesting()
    Dim Series() As String = ReceivedTextSeries.Split("#")
    If Series.Length = 4 Then
        UpdateTextBox(Series(0), TextBox1)
        UpdateTextBox(Series(2), TextBox2)

    End If
End Sub
相关问题