22332112
22332112

Reputation: 2397

Non blocking wait while reading data from serial in VB

I have a procedural GUI method that needs to retrieve data from serial several times.

Each time it does so, it needs to wait for serial data function to finish (e.g., that function works for 15 seconds by averaging all the data received from the serial).

What is some non blocking ways of waiting on this? At first I tried Threading.Thread.Sleep(15000), however this locks up the program completely.

I also tried very similar method (that still uses sleep but at smaller intervals). Blocking is still there, just at 0.5 seconds interval.

Public Sub ResponsiveSleep(ByRef iMilliSeconds As Integer)
    Dim i As Integer, iHalfSeconds As Integer = iMilliSeconds / 500
    For i = 1 To iHalfSeconds
        Threading.Thread.Sleep(500) : Application.DoEvents()
    Next i
End Sub

Should I make serial read function a separate thread before I call wait function?

Upvotes: 1

Views: 1338

Answers (2)

Athena
Athena

Reputation: 3228

Generally speaking I/O and any other blocking calls should be put on a separate thread. You might end up with something like:

Public Async Sub MyUserInterfaceEventThatMakesTheAsyncCallWork()
    Dim result as String = Await ResponsiveSleep()
    MyUserInterface.Text = result
End Sub

Public Async Function ResponsiveSleep() As Task(Of String)
    Await Task.Delay(10000) 'however long you want the delay to be, or delay logic here
    'Calls here should always be Await, or they'll be synchronous
    Return "the result of my thing!"
End Function

This is useful because you don't have to think too hard about it. As long as you're asynchronous in the other function, you can write it more or less as if it was synchronous.

Upvotes: 2

Alessandro Mandelli
Alessandro Mandelli

Reputation: 581

If data are received without polling, you might implement a DataReceived event. More info here https://msdn.microsoft.com/it-it/library/system.io.ports.serialport.datareceived(v=vs.110).aspx

Upvotes: 2

Related Questions