I\'m writing a Windows Service for communication with a Serial Mag-stripe reader and a relay board (access control system).
I run into problems where the code stops
You can't close someone elses connection to a port, the following code will never work:
if (serialPort.IsOpen) serialPort.Close();
Because your object didn't open the port you can't close it.
Also you should close and dispose the serial port even after exceptions occur
try
{
//do serial port stuff
}
finally
{
if(serialPort != null)
{
if(serialPort.IsOpen)
{
serialPort.Close();
}
serialPort.Dispose();
}
}
If you want the process to be interruptible then you should Check if the port is open and then back off for a period and then try again, something like.
while(serialPort.IsOpen)
{
Thread.Sleep(200);
}