串口接收数据与鼠标移动事件冲突怎么办
我在C#中用serialport控件实现了一个串口小程序,具体如下:
1.该程序每100ms发出一个命令给外部接收设备,由一个timer控制
2.设置串口接收的ReceivedBytesThreshold为1,即每接收到一个字节就触发DataReceive事件,DataReceive事件代码如下:
public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
long lExecuteTime = 0;
// modified trigger condition to maximum time
serialPort1.ReceivedBytesThreshold = serialPort1.ReadBufferSize;
int curbyte = serialPort1.ReadByte();
recvbuf[iCurPos++] = (byte)curbyte;
if (curbyte == 0x7E) // received a completed response
{
EndTime = DateTime.UtcNow;
timer_timeout.Enabled = false;
lExecuteTime = (EndTime.Ticks - StartTime.Ticks) / 10; // change to us
lb_time.Text = lExecuteTime.ToString() + " us";
InforDisplay(recvbuf, iCurPos);
iCurPos = 0;
}
else if (iCurPos > 79)
{
txtBox_Err.Text += "Error: Receive buffer over flow!\r\n";
iCurPos = 0;
}
// recover trigger condition to 1
serialPort1.ReceivedBytesThreshold = 1;
}
这其中调用了一个函数InfoDisplay, 这个函数用来将接收到的数据显示到界面上。
3. 问题:程序运行之后,命令收发正常,显示也正常;但是当鼠标在窗体上移动时,串口数据就会有丢失的可能,鼠标移动的越快,出错几率越大。我推断,鼠标移动时,程序要响应mousemove事件(我并没有处理这个事件),导致来不及响应datareceive事件,造成数据丢失
4. 从网上查,用多线程可以解决这个问题,但是我不知道该怎么设计这个多线程,请大家指点
多谢