在 VB 中从串口读取数据时非阻塞等待

Non blocking wait while reading data from serial in VB

我有一个程序化的 GUI 方法,需要多次从串行中检索数据。

每次这样做,都需要等待串口数据函数完成(例如,该函数通过对从串口接收到的所有数据进行平均来工作 15 秒)。

有哪些非阻塞的等待方式? 起初我尝试了 Threading.Thread.Sleep(15000),但是这完全锁定了程序。

我也试过非常相似的方法(仍然使用睡眠但间隔更小)。阻塞依然存在,只是间隔0.5秒。

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

我应该在调用等待函数之前将串行读取函数设为一个单独的线程吗?

如果在没有轮询的情况下接收到数据,您可以实施 DataReceived 事件。 更多信息在这里 https://msdn.microsoft.com/it-it/library/system.io.ports.serialport.datareceived(v=vs.110).aspx

一般来说 I/O 和任何其他阻塞调用都应该放在单独的线程上。你可能会得到类似这样的结果:

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

这很有用,因为您不必考虑太多。只要你在另一个函数中是异步的,你可以或多或少地把它写成同步的。