从VB中的串行读取数据时无阻塞等待 [英] Non blocking wait while reading data from serial in VB

查看:99
本文介绍了从VB中的串行读取数据时无阻塞等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个过程GUI方法,该方法需要多次从序列中检索数据.

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

每次这样做,都需要等待串行数据功能完成(例如,该功能通过平均从串行接收的所有数据,可以工作15秒).

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

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

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.

我也尝试了非常类似的方法(该方法仍然使用睡眠,但间隔较小).阻塞仍然存在,只是间隔为0.5秒.

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?

推荐答案

通常来说,I/O和任何其他阻塞调用应放在单独的线程上.您可能会遇到类似以下内容:

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.

这篇关于从VB中的串行读取数据时无阻塞等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆