旧数据出现在串口中 [英] old data appearing in serial port

查看:168
本文介绍了旧数据出现在串口中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi.,

I have written a code to read data from the serial continuously. But when running the code for long duration like 3-4 hours serial data receiving is not in corresponding to the data that is sent by the sender. If the same code is run for few min. it does not show any problem of that sort i.e, what the sender sends is immediately reflected at the serialport receive. please give any solution if available that does not make lose of data. here is the code for serial data receive

<pre lang="c#">th = new System.Threading.Thread(serialPort1_DataReceived);
                        th.IsBackground = true;
                        th.Start();





in serialPort1_DataReceived方法



in serialPort1_DataReceived method

RxString += serialPort1.ReadLine();
               DisplayText(RxString);




DisplayText方法中的
我做一些操作来拆分rxstring并将其显示在文本框中。



另外我需要知道为什么在使用像putty这样的超级终端时不会出现这个问题



提前感谢



in "DisplayText" method I do some operations to split "rxstring" and display it in a text box.

Also I need to know why this problem does not occurs when using hyper-terminal like "putty"

thanks in advance

推荐答案

如果没有DisplayText方法的代码,我们必须猜测 - 但我敢打赌它与+ =有关part:

Without the code fro teh "DisplayText" method, we have to guess - but I'd bet it has to do with the "+=" part:
RxString += serialPort1.ReadLine();

鉴于DataRecieved事件是在非UI线程上处理的,你的DisplayText方法正在使用控件(正如我所假设的那样,或者你会遇到交叉线程错误),那么UI线程很可能同时也在修改RxString - 这很危险,可能会导致所有类型间歇性的奇怪问题。



我建议你至少要考虑让所有的代码线程都安全。

Given that the DataRecieved event is handled on a non-UI thread, if your DisplayText method is using controls (as I would assume it does or you'd get cross threading errors) then there is a good chance that the UI thread is also modifying RxString at the same time - this is dangerous and can lead to all sorts of intermittent weird problems.

I would suggest that at a very minimum, you need to look at making all your code thread safe.


这篇关于旧数据出现在串口中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆