Problem to read Com port with while loop?

ken76

Member
Joined
Nov 15, 2018
Messages
23
Programming Experience
5-10
The while loop stop when data reads x, but the buttonTransfer button never gets enabled
and the MessageBox message never shows up, but the program does not either freeze. What can be the problem with this code?

C#:
 try
            {
                buttonTransfer.Enabled = false;
                port = new SerialPort();
                port.BaudRate = 9600;
                port.PortName = getValueNew;
                 port.Open();

                port.Write("1");
                ch = 1;

                while (data != "x")
                {
                    data = port.ReadLine();
                   this.Invoke(new EventHandler(displaydata_event));
                }

                buttonTransfer.Enabled = true;
                MessageBox.Show("Done!");
                port.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
 
Are you running that code in your UI thread? Or is it running in another thread? A background worker thread, a dedicated thread, or a threadpool thread?

My understanding is that ReadLine() on line 14 will block until an entire line is read in from the port. If you are saying that the program is not freezing, it almost sounds like you are running that code in another thread, but what is odd is that you should have gotten exceptions about trying to manipulate the UI from another thread when you disabled the button on line 3.
 
Back
Top Bottom