Alexander Stroborg Alexander Stroborg - 3 months ago 17
C# Question

Frozen windows form application with checkbox c#

Here is my situation, when I check the checkbox, my application freezes but still works. Which means that it is still able to recognize data sent through the serial port; for testing purposes it just exits the application.

If I comment out line 45 ("pipe = arduino.ReadLine();" see screenshot below) meaning that it no longer has to "ReadLine()", I am able to un-check the box. However now when I try to re-check the box, I get an error message saying "Access to the port 'COM5' is denied"

I assume that the code cannot continue because it is trying to "ReadLine()" when nothing has been sent through yet. However I do not have an explanation for being denied access to the COM port; rather than me trying to open the port when its already opened.

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";
}
}
}

Answer

The SerialPort class manages system resources and, when such sensitive objects are involved, the class usually implements the IDisposable interface to allow those system resource to be released immediately to the system.

Your code forgets to close the SerialPort, so, the next time your user action cause a call to this event handler the port is in use by your own first action.

Fortunately, there is an easy way to ensure proper closing and disposing of such objects and it is the 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";
    }
}