winform的串口通信程序,一共6个串口(1个物理串口,5个虚拟串口),在界面上拖了6个serialPort控件分别对应6个串口,其中serialPort1为物理串口。物理串口10秒接收一条数据,虚拟串口大概10到30分钟一条。在DataReceived事件里收到数据后通过control.invoke将其在界面上显示出现异常‘Invoke or BeginInvoke cannot be called on a control until the window handle has been created.’。出现异常的是物理串口,但自从这个异常出现后,物理串口仍然能正常接收数据,而其余5个虚拟串口确反而似乎收不到数据(表现是数据库没有记录),重启软件后正常。为什么会出现这种情况呢?
下面是DataReceived事件代码:
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(1000);
            try
            {
                if (serialPort1.BytesToRead == 0)
                {
                    return;
                }
                string s = "1";
                byte[] bytes = new byte[serialPort1.BytesToRead];
                try
                {
                    serialPort1.Read(bytes, 0, serialPort1.BytesToRead);
                }
                catch (Exception ee)
                {
                    return;
                }                string ss = "";
                for (int i = 0; i < bytes.Length; i++)
                {
                    ss += bytes[i].ToString("X2") + " ";
                }                ChangeText ct = new ChangeText(SetRichTextBox);
                richTextBox_content.Invoke(ct, ss);                //下面是启动线程及准备线程所需参数
                StructModel.comSendTo comsendto = new StructModel.comSendTo();
                comsendto.oreceiveBytes = bytes;
                comsendto.sender = sender;
                comsendto.receiveBytesLength = Convert.ToUInt16(bytes.Length);                Thread t1 = new Thread(new ParameterizedThreadStart(DoWork_com_10s));
                t1.IsBackground = true;
                t1.Start(comsendto);                serialPort1.ReceivedBytesThreshold = 1;
            }
            catch (Exception ex)
            {
                WriteToFile_DataReceive(" DATARECEIVE " + ex.Message);
            }
        }