0

I have a program based on Windows Form Application in C#. I need to read data from Serial Port(Com Port). For this purpose, I need to use Threads and Serial Ports in C#. My program follows the following sequence.

  1. First it initializes the thread which is the Foreground thread.
  2. It will check that the serial port is open or not and then start reading the program.

All of the programs are working fine but After clicking on the close button I got this error at this line 'string machine_data = serialPort1.ReadTo("\u0003");'

Here is the Snapshot of my error:

I also tried this method to close Thread. And I also used this method to Terminate Threads in close function.

  • The while loop is searching the port multiple times so you need to break out of for loop after string is found. You code will only work if the string is at the end of the port data. You will get an exception under the following conditions 1) System.ArgumentException: 2) The length of the value parameter is 0. 3)System.ArgumentNullException: The value parameter is null. 4) System.InvalidOperationException: The specified port is not open. 5) System.TimeoutException: The operation did not complete before the time-out period ended. – jdweng Dec 24 '20 at 11:02
  • Hard to help you without any relevant code, but from your explanation it sounds like the serial port object is still trying to do a read even after the thread has been disposed. I would recommend in your OnClose event handler, if the serial port is open, to close and dispose of it before terminating the form. – Baddack Dec 30 '20 at 20:12
  • You don't need to mess with the thread, windows will handle that for you. You just need to disconnect your serial port before windows closes the thread. – Baddack Dec 30 '20 at 20:18

0 Answers0