System.Threading.Timer 和 SerialPort 读取

发布于 2024-10-20 18:41:35 字数 538 浏览 3 评论 0原文

我的应用程序每 x 毫秒从串行端口(MyDataReader)读取一些数据并将其显示在控件上,MyDataReader 也可以是一个文件,我可以从中读取数据。

我使用了一个简单的计时器,每次滴答声我都会从串行端口/文件读取数据,处理并显示它,效果很好。

现在我添加了另一个需要从中读取数据的设备,并且已切换到 System.Threading.Timer,但现在我的“tick”功能无法正常工作,当它从串行端口读取时,我得到零。当我进入调试模式并断点 ReadFromSerialPort() 函数时,有时我会得到有效数据,有时却不会。

如果我将读取从串行端口切换为从文件读取,它工作正常,我已经调用了所有显示数据的控件。

我锁定了串行端口的读/写:

lock(this)
{
    writetoserialport;
    readfromserialport;
}

任何人都知道为什么我总是得到零,并且当我断点时有时会有数据? 这就像它在不同的线程上打开从串行端口的读取,我需要等待数据被读取。

谢谢。

My application reads every x ms some data from a serial port(MyDataReader) and displays it on a control, MyDataReader also can be a file, from which I can read data.

I used a simple timer, every tick I've read the data from the serial port/file, processed it and displayed it, It worked great.

Now I've added another device from which I need to read data and I've switched to System.Threading.Timer, but now my "tick" function is not working properly, when it reads from the serial port, I get zeros. when I enter debug mode and breakpoint ReadFromSerialPort() function, sometimes I get valid data, sometimes I don't.

If I switch the reading from serialport to read from file it works fine, I've invoked all the controls that display data.

I locked the read/write from the serialport:

lock(this)
{
    writetoserialport;
    readfromserialport;
}

anyone have any idea why I get zeros all the time, and when I breakpoint I have sometimes data?
It's like it opens the read from serial port on different thread and I need to wait to the data to be read.

Thank you.

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

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

发布评论

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

评论(2

薄情伤 2024-10-27 18:41:35

嗯,串行端口与文件不同。

文件数据存储在磁盘上,如果文件没有被截断,您可以稍后获取。
数据可以来自串行端口,但可能无法捕获。

因此必须从串口捕获数据并将其存储在缓冲区中。
然后计时器将从缓冲区获取数据。

如果这不是您的问题,请告诉我们更多信息。

Well, a serial port is not the same as a file.

The file data is stored on disk and if the file is not truncated, you can get it later.
Data can come from serial port and may not be captured.

So you must capture data from the serial port and store it in a buffer.
Then the timer will get data from your buffer.

If this is not your problem, tell us more.

冷情 2024-10-27 18:41:35

串行端口的读取是不确定的。当您执行读函数时,端口中可能没有数据。您是否在实际执行读取功能之前检查是否有数据要读取?

如果设置断点,由于调试速度不同,有时会看到数据。

Reading for a serial port is not deterministic. At the moment you are executing the read function, there may not be data in the port. Are you checking if there is data to be read before actually executing the read function?

In case of putting in breakpoint, because the speed of debugging varies, you sometimes see data.

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