noidea noidea - 1 month ago 15
Vb.net Question

How to multithread using serial connection vb.net

I have a serial connection to a remote machine and i'm developing a windows form using vb.net in order to gather some infos.

So as u can see in the code below i'm waiting until i receive the full string ( length 4, # as separator ) to change some textboxes text.

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


But i'm getting an error saying that multithreading isn't allowed..
The operation between threads is not valid: Control 'TextBox1' accessed from a thread other than the thread where it was created.


How can i manage this now? I've tried to add event handlers to avoid this but without success..

Answer

So you could create a quick sub that invokes your textboxes. You're already doing that in your previous method. This makes it reusable.

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

Then all your calls to write to a textbox can be called with

UpdateTextBox("My Text", TextBox1)

So with your code you could do

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
Comments