Problem to read Com port with while loop?

Ken Ekholm 151 Reputation points
2022-04-11T10:40:53.77+00:00

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?

 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);
            }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes