-1

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..

noidea
  • 184
  • 5
  • 22
  • Check if Textbox1 requires invoking an invoke it? – Malcor Oct 07 '16 at 11:40
  • @Malcor what do you mean with "requires invoking" ? – noidea Oct 07 '16 at 11:53
  • check this out: http://stackoverflow.com/questions/10775367/cross-thread-operation-not-valid-control-textbox1-accessed-from-a-thread-othe – Keith Mifsud Oct 07 '16 at 11:55
  • well you are already doing it with `TextBoxConsola`. Do it with `TextBox1` and `TextBox2` as well – Keith Mifsud Oct 07 '16 at 11:57
  • Possible duplicate of [Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on](http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the) – the_lotus Oct 07 '16 at 12:37
  • @the_lotus the fact that it is vb.net is enough to not being a duplicate.. thank you all – noidea Oct 07 '16 at 13:13

1 Answers1

1

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
Malcor
  • 2,667
  • 21
  • 29