本文介绍了当字节可用时,.Net SerialPort 需要 0.5 秒以上的时间来读取字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C# 中使用 .Net SerialPort 类从端口读取字节.收到 DataReceived 事件后,我检查串行端口以查看是否可以读取字节.但是,即使字节可用,端口也可能需要半秒以上才能读取单个字节.代码大致如下:

I'm using the .Net SerialPort class in C# to read bytes from a port. On receipt of a DataReceived event I check the serial port to see if bytes are available to be read. However, even if bytes are available, the port can take over half a second to read a single byte. Code is roughtly as follows:

...
while(Port.BytesToRead > 0)
{
    StopWatch.Restart();
    Int32 BytesRead = Port.Read(Read, 0, 1);
    StopWatch.Stop();
    if (StopWatch.ElapsedMilliseconds > 100)
    {
    // Record the time. The stopwatch code
    // was only added after performance issues were observed.
    }
}

请注意,我测量的时间不是读取所有字节的时间,而是读取单个字节的时间.我经常会收到一个 DataReceived 事件,并且必须等待 0.5 秒才能读取第一个字节.

Note that the time which I've measured is not the time to read all bytes, rather the time to read a single byte. Frequently I'll receive a DataReceived event and have to wait 0.5 seconds for the first byte to be read.

我实际上尝试将 Port 的 ReadTimeout 属性设置为较小的值,以防止它无限期地坐在那里,但此属性似乎被忽略了.

I've actually tried setting the Port's ReadTimeout property to something smaller to prevent it from sitting there indefinitely, but this property seems to be ignored.

非常感谢任何帮助.

推荐答案

结果是连接到调试器的运行导致了问题.在调试器之外运行时,记录读取一个字节的最长时间约为 20 毫秒,而在调试器内运行时(无断点、条件或以其他方式启用)则高达 700 毫秒.

Turns out that running connected to the Debugger was causing the problem. Running outside of the debugger the maximum time recorded to read a byte was around 20ms, as opposed to up to 700ms when running within (no breakpoints, conditional or otherwise enabled).

有点小题大做,因为运行发布版本时通信问题的真正原因可能在别处.

Bit of a red herring, as the real cause of the comms problem when running a release build probably lay elsewhere.

这篇关于当字节可用时,.Net SerialPort 需要 0.5 秒以上的时间来读取字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 04:21