I am using a .net SerialPort
as property in a class for communication with some hardware. If I close the program I need to send a stop command before I close the connection.
I thought that the most elegant way would be to do this in my decontructor of the class I wrote but I had to find out that my SerialPort
is closed at the time the decontrcutor is fired and cannot be opend again.
Here is a test class I wrote which produces the same error:
public class SerialPortTestClass
{
private System.IO.Ports.SerialPort ComPort { get; set; }
public SerialPortTestClass()
{
ComPort = new System.IO.Ports.SerialPort
{
BaudRate = 38400,
StopBits = System.IO.Ports.StopBits.One,
NewLine = ((char)19).ToString(),
Parity = System.IO.Ports.Parity.None,
Handshake = System.IO.Ports.Handshake.None,
RtsEnable = false,
ReadBufferSize = 512,
ReadTimeout = 5000,
ReceivedBytesThreshold = 1
};
}
public void Connect(string port)
{
ComPort.PortName = port;
ComPort.Open();
}
public void Disconnect()
{
var bytes = new byte[] { 83, 80, 32, 115, 54, 19 };
ComPort.Write(bytes, 0, bytes.Length);
ComPort.Close();
}
~SerialPortTestClass()
{
if (ComPort.IsOpen)
Disconnect();
}
}
Has anybody an idea why the SerialPort is closed and how to fix this behavior?