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

Posted by karthik on Stack Overflow See other posts from Stack Overflow or by karthik
Published on 2010-04-08T07:00:54Z Indexed on 2010/04/08 7:03 UTC
Read the original article Hit count: 267

Filed under:
|

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 the 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);

                    }
                }           
            }
        }
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about serial-port