I have written a program to receive data from the serial port. I am doing some calculations using those data and writing results to 4 richTestBoxes real time.I have two buttons to open and close the serial port. Some times when the close button is pressed, the form get stucked.This is the code in the close button.But this is not happening every time.

private void btnClosePort_Click(object sender, EventArgs e)
comport.Close(); // comport is the object created in the class serialport

I think the reason is that many fuinctions are running while the port is being closed. Is there any method to stop all the current processes in the program and then close the comport????? or any other solution????

8 Years
Discussion Span
Last Post by dilansankalpa

It is possible that you have a read or write action in the UI thread that is hanging because you have closed the serial port.
I recommend that you set a flag before closing the port and pause for a short time to allow other threads to finish whatever they are doing.
Ideally you should be using some interlocking to prevent multiple threads accessing the comport device simultaneously.
I generally do this by wrapping my serial port in a seperate class and using an object lock.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.