Wesley Carlsen
Wesley Carlsen

Reputation: 137

Constantly check SerialPort object to see if any bytes exist and if so read bytes and perform function

I am interfacing with a device, and need a way to constantly check if any bytes are available to be read by the serialport, and if so I need to read them and perform different functions. I can't create a data_received event for a number of reasons due to the project I am working on. As of now I have an infinite for loop running in a new thread, but it is causing the computer to slow way down.

Does anyone have any other ideas? Any help is appreciated. Below is the for loop code I am currently using.

void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        object[] parameters = (object[])e.Argument;
        SerialPort port = (SerialPort)parameters[0];
        agentRadio agentR = (agentRadio)parameters[1];

        for (; ; )
        {
            if (port.IsOpen)
            {
                try
                {
                    if (port.BytesToRead > 0)
                    {
                        byte value = (byte)port.ReadByte();

                        if (value == Global.OFF_CHAR)
                        {
                            port.Close();
                            Global.isConnected = false;
                            Form form = new Form();
                            form.deviceDisconnect(agentR);

                            MessageBox.Show("Your device has disconnected on its own, due to inactivity or because a key was switched off.", "Device Disconnect", MessageBoxButton.OK, MessageBoxImage.Information);

                            break;
                        }
                        else if (value == Global.WARNING_CHAR[0])
                        {
                            if (Global.activeClick)
                            {
                                port.BaseStream.Write(Global.POLL_CHAR, 0, Global.POLL_CHAR.Length);
                            }
                        }
                    }
                }
                catch {  }
            }
            else
            {
                break;
            }
        }
    }

Upvotes: 0

Views: 4111

Answers (2)

Peter Ritchie
Peter Ritchie

Reputation: 35881

Use the DataReceived event. This event is called on a secondary thread, there's no need to create another, or event a BackgroundWorker.

Upvotes: 0

Martin James
Martin James

Reputation: 24847

Get rid of the horrible 'if (port.BytesToRead > 0)' polling loop! Why do you do that - you do nothing else if the check retuns false, so just let the read block in the normal way.

Upvotes: 2

Related Questions