我正在从串行端口读取数据.数据脱离了规模.我现在使用Readline(),并且即使在我删除了DiscardInBuffer()之后,也会丢失数据.
从串行端口读取数据的正确方法是什么?网上有这么少的例子,我觉得这就像一些没有人想到的圣杯.
从串行端口读取数据的正确方法是什么?网上有这么少的例子,我觉得这就像一些没有人想到的圣杯.
请帮忙吗
像串口似乎是一个反复无常的孩子.
C#,WinCE 5.0,HP瘦客户端,Compact框架2.0
- private void WeighSample()
- {
- this._processingDone = false;
- this._workerThread = new Thread(CaptureWeight);
- this._workerThread.IsBackground = true;
- this._workerThread.Start();
- } //end of WeighSample()
- private void CaptureWeight()
- {
- globalCounter++;
- string value = "";
- while (!this._processingDone)
- {
- try
- {
- value = this._sp.ReadLine();
- if (value != "")
- {
- if (value == "ES")
- {
- _sp.DiscardInBuffer();
- value = "";
- }
- else
- {
- this.Invoke(this.OnDataAcquiredEvent,new object[] { value });
- }
- }
- }
- catch (TimeoutException)
- {
- //catch it but do nothing
- }
- catch
- {
- //reset the port here?
- MessageBox.Show("some other than timeout exception thrown while reading serial port");
- }
- }
- } //end of CaptureWeight()
需要注意的是我的应用程序是当光标跳到文本框时启动线程(weightSample).这样做的原因是重量也可以手动输入(部分req的).所以我不提前知道用户是否要在平衡上按PRINT或键入重量.在获取数据后的任何一种情况下,我退出工作线程.另外请注意,我没有使用串口事件DataReceived,因为我被告知不可靠.
任何意见/想法欢迎.这是我第一次使用串口.
解决方法
我从来没有运气ReadLine工作.只要在数据可用时读取本地缓冲区,然后使用单独的线程扫描数据并自行查找换行符.