开发者

Thread to receive the messages from serial port is not working using c#

I am using Serial port to receive the messages. The below function is running in a thread. When i debug i find that the thread is running properly. But "if (sp.IsOpen)" is always false, due to which the code is not executing inside the IF condition at all. It says the Port is closed.

I will be having multiple serial ports in my system and i will not know, which port will receive t开发者_如何学JAVAhe message. So i need to listen to all the ports in one Thread.

How can i solve my problem here ?

 private void ListenerPorts()
    {

        log.Info("Listening Thread Started");

        while (true)
        {
            //foreach (SerialPort sp in storeport)
            foreach (SerialPort sp in comPortsList)
            {

                if (sp.IsOpen)
                {
                    sp.ReadTimeout = readTimeoutInMs;
                    sp.WriteTimeout = writeTimeoutInMs;

                    try
                    {
                        string msg = sp.ReadLine();
                        this.GetMessageRichTextBox("Message : " + msg + "\n");
                        sp.WriteLine(sp.PortName);

                        if (msg.Contains("COM"))
                        {
                            // is AutoScan
                            receiverPortName = sp.ReadLine();
                            this.updateLblStatusRichTextBox(sp.PortName + " is connected to " + msg + "\n");
                        }
                        else
                        {
                            //standalone is uppercase
                            ReceiverPortName = sp.ReadLine();
                            this.updateLblStatusRichTextBox(sp.PortName + " is connected to " + ReceiverPortName + "\n");

                        }
                    }

                    catch (Exception ex)
                    {
                        // no data
                        System.Diagnostics.Debug.WriteLine(sp.PortName + " : " + ex.Message);

                    }
                }           
            }
        }
    }


Where's your initialization code for the serial ports? And in particular the line SerialPort.Open();?

Take a look at using

SerialPort.DataReceived += 
  new SerialDataReceivedEventHandler(SerialDataReceivedEventHandler);

to receive the data from them instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜