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

前端 未结 9 1401
心在旅途
心在旅途 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:52

    This code seems to work properly. I've tested it on my local machine in a console application, using Procomm Plus to open/close the port, and the program keeps on ticking.

        using (SerialPort port = new SerialPort("COM1", 9600))
        {
            while (true)
            {
                Thread.Sleep(1000);
                try
                {
                    Console.Write("Open...");
                    port.Open();
                    port.DtrEnable = true;
                    Thread.Sleep(1000);
                    port.Close();
                    Console.WriteLine("Close");
                }
                catch
                {
                    Console.WriteLine("Error opening serial port");
                }
                finally
                {
                    if (port.IsOpen)
                        port.Close();
                }
            }
        }
    

提交回复
热议问题