为什么我的Winform冻结,我无法关闭串行端口?

时间:2019-07-18 16:41:35

标签: c# winforms serial-port

我有一个WinForm,它通过串行端口绘制来自Arduino的实时数据。 我有一个“ GetData”按钮来开始接收数据并绘制数据,而我有一个“ Stop”按钮来停止接收/绘图操作。接收和绘图工作正常。

为什么我的“停止”按钮不起作用?看来该应用程序在接收和绘图时被冻结了,不允许我停止它。

private void GetData_Click(object sender, EventArgs e)
        {

            serialPort.BaudRate = Convert.ToInt32(BaudRates.Text);
            serialPort.PortName = COMPorts.Text;
            textBox1.Text = "COM Port : " + COMPorts.Text + " <<=>> " + "Baud Rate : " + BaudRates.Text;
            COMPortOK.Enabled = false;
            GetData.Enabled = false;
            Stop.Enabled = true;
            try
            {
                serialPort.Open();
                textBox1.Text = "Port " + COMPorts.Text + " has been opened successfully.";

            }
            catch (System.IO.IOException ioe)
            {
                textBox1.Text = "Couldn't open COM port " + COMPorts.Text;
                MessageBox.Show("Couldn't open COM port." + "\n" + "System threw exception :" + ioe);
            }
            while (Stop.Enabled & !GetData.Enabled)
            {
                string serstr = serialPort.ReadLine();
                textBox2.AppendText(serstr + "\n");
            }
        }

        private void Stop_Click(object sender, EventArgs e)
        {
            serialPort.Close();
            GetData.Enabled = true;
            Stop.Enabled = false;
        }

0 个答案:

没有答案