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????

Dani AI

Generated

Freezing when closing a SerialPort in a WinForms app is usually caused by a thread interaction: the port raises DataReceived on a non-UI thread, and if that handler performs a synchronous UI call or holds a lock while the UI thread calls Close(), both sides can block. This behavior is explained in the SerialPort.DataReceived documentation and in the WinForms thread-safety guidance (SerialPort.DataReceived, ).

A practical shutdown sequence that avoids the common deadlock:

  • mark a volatile closing flag,
  • unsubscribe the DataReceived handler,
  • let any in-progress handler finish (signal/wait with a timeout), and
  • then call Close/Dispose.

Using asynchronous UI posting (BeginInvoke) from the background handler or queueing received data to be drained on the UI thread prevents the handler from blocking on the UI. Example pattern:

private volatile bool _closing;
private ManualResetEventSlim _handlerDone = new ManualResetEventSlim(true);

private void Serial_DataReceived(object s, SerialDataReceivedEventArgs e)
{
    if (_closing) return;
    _handlerDone.Reset();
    try
    {
        string chunk = serialPort.ReadExisting();
        this.BeginInvoke((Action)(() =>
        {
            if (_closing) return;
            richTextBox1.AppendText(chunk);
            // update other boxes...
        }));
    }
    finally { _handlerDone.Set(); }
}

private void SafeClose()
{
    _closing = true;
    serialPort.DataReceived -= Serial_DataReceived;
    _handlerDone.Wait(500); // small timeout to avoid indefinite block
    serialPort.Close();
    serialPort.Dispose();
}

As noted, interlocking is useful; prefer nonblocking UI updates or a producer/consumer queue for robustness. If synchronous reads are used, consider asynchronous reads with cancellation (BaseStream) on newer .NET versions or set short timeouts and log any timeouts during shutdown.

Recommended Answers

All 2 Replies

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.

thnaxx nick...!!! I'll try this.....!!! let u know if theres any problem further...!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.