Click here to Skip to main content
15,881,516 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying go get "OK" through Serial Port to vb.net, and VB.net check that "OK" and assign that value to string variable called - check_OK then i check that value with do loop.

What I have tried:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub
Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
    ReceivedText(SerialPort1.ReadExisting())
End Sub
Private Sub ReceivedText(ByVal text As String)
    If Me.RichTextBox1.InvokeRequired Then
        Dim x As New SetTextCallback(AddressOf ReceivedText)
        Me.Invoke(x, New Object() {(text)})
    Else
        Me.RichTextBox1.Text &= text
        Me.Label1.Text &= text
        If RichTextBox1.Text = "OK" Then
            OK_rs = 1
            RichTextBox1.Text = ""
        End If
    End If

End Sub
Delegate Sub SetTextCallback(ByVal text As String)


and here i check what we assign to check_OK
Do
              If OK_rs = 1 Then Exit Do
          Loop
          OK_rs = 0
Posted
Updated 6-Jun-17 0:42am

1 solution

The problem is probably exactly where you are doing that Do loop: if that's on the UI thread, then the Invoke from the DataReceived event will never happen because the thread is fully occupied checking the status of your flag variable.
While you can probably get round that by using DoEvents, it's a poor idea and isn't guaranteed to succeed - I've never tried it because if your code needs DoEvents then it's badly designed!
Instead of a loop, use a Timer: set it to 1/10th of a second, and in the Tick handler check your flag.
Continuous oops in Windows apps are always a bad idea, unless you have spun off a thread specifically to handle the loop (and even then you need to approach them with caution).
When you add in that the release version will quite likely not work either because the increased optimisation in release builds may well remove the loop completely, and it really isn't a good idea!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900