冻结 windows 带有复选框的表单应用程序#

Frozen windows form application with checkbox c#

这是我的情况,当我选中复选框时,我的应用程序冻结但仍然有效。即仍然可以识别通过串口发送的数据;出于测试目的,它只是退出应用程序。

如果我注释掉第 45 行("pipe = arduino.ReadLine();" 请参阅下面的屏幕截图)意味着它不再需要 "ReadLine()",我可以取消选中该框。但是现在当我尝试重新选中该框时,我收到一条错误消息说 "Access to the port 'COM5' is denied"

我假设代码无法继续,因为它正在尝试 "ReadLine()" 但尚未发送任何内容。但是我没有关于被拒绝访问 COM 端口的解释;而不是我在端口已经打开时尝试打开它。

private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {

        SerialPort arduino = new SerialPort();
        arduino.BaudRate = 9600;
        arduino.PortName = comboBox1.Text;
        string pipe;

        if (checkBox1.Checked)
        {
            checkBox1.Text = "Listening...";
            arduino.Open();
                pipe = arduino.ReadLine();
                if (pipe == "S\r")
                {
                    //System.Diagnostics.Process.Start("shutdown", "/f /r /t 0");
                    System.Windows.Forms.Application.Exit();
                }
        else
        {
            checkBox1.Text = "Start";
        }
    }
}

SerialPort class 管理系统资源,当涉及此类敏感对象时,class 通常实现 IDisposable 接口以允许这些系统资源立即释放给系统。

您的代码忘记关闭 SerialPort,因此,下次您的用户操作导致调用此事件处理程序时,您自己的第一个操作正在使用该端口。

幸运的是,有一种简单的方法可以确保正确关闭和处理此类对象,那就是 using statement

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{

    if (checkBox1.Checked)
    {
        checkBox1.Text = "Listening...";
        using(SerialPort arduino = new SerialPort())
        {
           arduino.BaudRate = 9600;
           arduino.PortName = comboBox1.Text;
           string pipe;
           arduino.Open();
           pipe = arduino.ReadLine();
           if (pipe == "S\r")
           {

                //System.Diagnostics.Process.Start("shutdown", "/f /r /t 0");
                //System.Windows.Forms.Application.Exit();
           }
       } // Here the port will be closed and disposed.
    }
    else
    {
        checkBox1.Text = "Start";
    }
}