本文介绍了有没有办法确定在 C# 中从 SerialPort 读取时是否没有剩余数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 SerialPort 读取数据,而我现在要做的是每 100 毫秒轮询一次 SerialPort 并查看它是否包含任何剩余数据.

I'm trying to read data from SerialPort and what I'm now trying to do is to poll the SerialPort every 100ms and see if it contains any remaining data.

    public static async Task<string> ReadRemaining(SerialPort port)
    {
        int prevBytesToRead = 0;
        await Task.Delay(100);
        while (prevBytesToRead != port.BytesToRead || port.BytesToRead == 0)
        {
            prevBytesToRead = port.BytesToRead;
            await Task.Delay(100);
        }
        return port.ReadExisting();
    }

我觉得这非常低效.有没有更好的办法?

I feel this is very inefficient. Is there a better way?

推荐答案

您已经在使用 BytesToRead 属性,这并不是最好的方法,但我猜猜它对你有用.

You already are using the BytesToRead property, which is not really the best approach, but I guess it is working for you.

您似乎在询问对未来的预测,您询问的是尚未从其他设备发送的数据.串口无法知道这一点.可能基于您的应用程序协议,其他设备会告诉您何时完成发送(消息结束标记),或者可能会告诉您消息将持续多长时间.

You appear to be asking for a prediction of the future, you're asking about data that hasn't yet been sent from the other device. There's no way for the serial port to know that. Perhaps based on your application protocol, the other device tells you when it is done sending (end of message marker) or perhaps told you how long the message would be.

你必须弄清楚如何重新表述这个问题,这样它就不需要预言未来.

You have to figure out how to rephrase the question so it doesn't require prophesying the future.

使用串口和 C# 异步的简洁方法是调用 port.BaseStream.ReadAsync.确保正确设置超时.在 Win32 超时下,您可以检测流中通常对应于消息边界的间隙,遗憾的是 .NET SerialPort 不允许这样做.但是您仍然可以为 ReadTimeout 属性找到比默认值更好的值.

The clean way to use serial ports and C# async is to call port.BaseStream.ReadAsync. Make sure the timeouts are set properly. Under Win32 timeouts you can detect gaps in the stream which often correspond to message boundaries, sadly .NET SerialPort doesn't allow that. But you still can find a better value for the ReadTimeout property than the default.

这篇关于有没有办法确定在 C# 中从 SerialPort 读取时是否没有剩余数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 06:54