Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SerialPortBase.SerialPortRead读取数据出现问题 #36

Open
zichen-ye opened this issue May 4, 2023 · 0 comments
Open

SerialPortBase.SerialPortRead读取数据出现问题 #36

zichen-ye opened this issue May 4, 2023 · 0 comments

Comments

@zichen-ye
Copy link

zichen-ye commented May 4, 2023

问题描述:使用过程中有些硬件设备读取不到数据或数据不完整
可能会出现“判断超时的循环”直接跳过的情况猜测:
1、var tempBufferLength = serialPort.BytesToRead;与tempBufferLength != serialPort.BytesToRead判断中间没有等待时间,serialPort.BytesToRead != 0使,很可能直接略过循环,使得数据读取不完整
2、Thread.Sleep(20);这个等待时间很短,也有可能导致bytesToRead != serialPort.BytesToRead这个判断不成立直接跳出循环的情况,使得数据读取不完整
3、建议var tempBufferLength = serialPort.BytesToRead;改为var tempBufferLength = 0; 并且延时处理的时间加长一些
对应源码:
protected Result<byte[]> SerialPortRead(SerialPort serialPort) { Result<byte[]> result = new Result<byte[]>(); DateTime beginTime = DateTime.Now; var tempBufferLength = serialPort.BytesToRead; //在(没有取到数据或BytesToRead在继续读取)且没有超时的情况,延时处理 while ((serialPort.BytesToRead == 0 || tempBufferLength != serialPort.BytesToRead) && DateTime.Now - beginTime <= TimeSpan.FromMilliseconds(serialPort.ReadTimeout)) { tempBufferLength = serialPort.BytesToRead; //延时处理 Thread.Sleep(20); } byte[] buffer = new byte[serialPort.BytesToRead]; var receiveFinish = 0; while (receiveFinish < buffer.Length) { var readLeng = serialPort.Read(buffer, receiveFinish, buffer.Length); if (readLeng == 0) { result.Value = null; return result.EndTime(); } receiveFinish += readLeng; } result.Value = buffer; return result.EndTime(); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant