When using the SerialPort class development program on a platform recently, it was discovered that the program would exit abnormally when using the SerialPort class, and, oddly, the exception could not be caught even if all the code for the serial port was placed in the try{}catch{} block. Finally, a solution was found in a foreign forum.
Comport.open ();
Gc. SuppressFinalize (comport. BaseStream);
that is, after opening the serial port, immediately call Gc.suppressfinalize (comport. BaseStream); This function prevents the garbage collector from reclaiming the stream object inside the SerialPort class. The problem is solved. The cause of the problem I don't know, it could be. NET or a bug in the serial port driver. In addition, Gc.reregisterforfinalize (comport) should theoretically be called before the serial port is closed. BaseStream); comport. Close (); This allows the garbage collector to reclaim the stream object inside the SerialPort class. But someone called the close () function and got the exception that could not be caught. So I didn't use it. Moreover, my program will not shut down the serial port until it terminates, and there will be no excessive testing of this line of code.
. Net C # serial Serialort safe handle has been closed problem resolution