Non blocking wait while reading data from serial in VB

浪尽此生 提交于 2019-12-11 06:11:22

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/45572607/non-blocking-wait-while-reading-data-from-serial-in-vb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!