This is a flaw in the SerialPort class; it uses an internal auxiliary thread to wait for events on the port. The event source is DataReceived, PinChanged, and ErrorReceived. The disadvantage is the implementation of the Close () method; it does not wait for the completion of this auxiliary stream. It takes time, the exact time is not predictable, and can be many seconds when the machine is especially busy. The physical port does not close until this happens, opening the port before the thread exits the bombs with the exception of the "port already in use" exception. The one you get. Thus, sleeping for 300 ms is not enough.
This is usually not a problem; serial ports are not compatible devices. Closing the serial port rather than exiting your program is dangerous; another process might steal the port. This exception is also given to you when you try to open it again. A common practice is to open the port at application startup and not close it until it is completed.
Hans passant
source share