使用串行端口时控制台 CTRL-C 处理失败

发布于 2024-08-16 12:15:25 字数 651 浏览 5 评论 0原文

使用 VB.Net,我添加了一个 CTRL-C 处理程序:

 AddHandler Console.CancelKeyPress, AddressOf QuitHandler

它执行以下操作:

Private Sub QuitHandler(ByVal sender As Object, ByVal args As ConsoleCancelEventArgs)

        Console.WriteLine("Quitting...")
        args.Cancel = True
        Quit = True
    End Sub

然后我有一个主循环,该循环一直运行到 Quit=True。

这一切都有效,直到我开始从串行端口读取数据:

 Private Sub port_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles Port.DataReceived

此时 CTRL-C 处理程序将被忽略大约 30 秒,此时控制台应用程序将终止而不执行清理代码。

为什么?

Using VB.Net I've added a CTRL-C handler:

 AddHandler Console.CancelKeyPress, AddressOf QuitHandler

Which does the following:

Private Sub QuitHandler(ByVal sender As Object, ByVal args As ConsoleCancelEventArgs)

        Console.WriteLine("Quitting...")
        args.Cancel = True
        Quit = True
    End Sub

I then have a main loop which just runs until Quit=True.

This all works until I start reading from the serial port:

 Private Sub port_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles Port.DataReceived

at which point the CTRL-C handler gets ignored for about 30secs at which point the console app just terminates without going through the cleanup code.

Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

栀梦 2024-08-23 12:15:25

我不懂VB,但我的猜测是你试图从不存在的串行端口读取数据(呃,端口在那里,数据不在那里);因此,您的程序将阻塞(“挂起”),直到读取尝试在 30 秒后超时。

如果我是正确的,您需要某种方法来轮询串行输入而不会阻塞,或者(更好)在数据实际出现时调用异步子程序。

I don't know VB, but my guess would be that you're attempting to read data from the serial port that isn't there (err, the port is there, the data isn't); as a result, your program is blocking ("hanging") until the read attempt times out after 30 seconds.

If I'm correct, you need some way to poll your serial input without blocking, or (better) to get an asynchronous sub called when data actually appears.

撞了怀 2024-08-23 12:15:25

您应该确保了解超时是如何工作的,因为您正在读取池上的串行端口。您的串行线程将始终运行并尝试读取某些内容。

最好的方法是在数据可用时读取数据,然后您的串行线程就有时间喘息。

您还可以尝试使用 DoEvents。

You should make sure to understand how Timeouts work, since you are reading serial port on pooling. Your serial thread will always be running and trying to read something.

A best approuch would be to read data just when its availiable, then your serial thread would have time to breath.

You can also try to use DoEvents.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文