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

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

    How to do reliable async comms

    Don't use the blocking methods, the internal helper class has some subtle bugs.

    Use APM with a session state class, instances of which manage a buffer and buffer cursor shared across calls, and a callback implementation that wraps EndRead in a try...catch. In normal operation, the last thing the try block should do is set up the next overlapped I/O callback with a call to BeginRead().

    When things go awry, catch should asynchronously invoke a delegate to a restart method. The callback implementation should exit immediately after the catch block so that the restart logic can destroy the current session (session state is almost certainly corrupt) and create a new session. The restart method must not be implemented on the session state class because this would prevent it from destroying and recreating the session.

    When the SerialPort object is closed (which will happen when the application exits) there may well be a pending I/O operation. When this is so, closing the SerialPort will trigger the callback, and under these conditions EndRead will throw an exception that is indistinguishable from a general comms shitfit. You should set a flag in your session state to inhibit the restart behaviour in the catch block. This will stop your restart method from interfering with natural shutdown.

    This architecture can be relied upon not to hold onto the SerialPort object unexpectedly.

    The restart method manages the closing and re-opening of the serial port object. After you call Close() on the SerialPort object, call Thread.Sleep(5) to give it a chance to let go. It is possible for something else to grab the port, so be ready to deal with this while re-opening it.

提交回复
热议问题