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

前端 未结 9 1443
心在旅途
心在旅途 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条回答
  •  旧时难觅i
    2020-12-23 10:54

    Have you tried leaving the port open in your application, and just turning DtrEnable on/off, and then closing the port when your application closes? i.e:

    using (SerialPort serialPort = new SerialPort("COM1", 9600))
    {
        serialPort.Open();
        while (true)
        {
            Thread.Sleep(1000);
            serialPort.DtrEnable = true;
            Thread.Sleep(1000);
            serialPort.DtrEnable = false;
        }
        serialPort.Close();
    }
    

    I'm not familiar with DTR semantics, so I don't know if this would work.

提交回复
热议问题