How to do robust SerialPort programming with .NET / C#?

前端 未结 9 1442
心在旅途
心在旅途 2020-12-23 10:22

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

9条回答
  •  时光取名叫无心
    2020-12-23 10:43

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

提交回复
热议问题