views:

356

answers:

2

I have an app where I read from the serialport, everything goes fine, until I close the app. When I click on the [X] the app simply hangs, the UI: unresponsive.

I read from the port in the DataReceived event handler, and I close the port when FormClosed happens:

    private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        mySerialPort.Close();
    }
+3  A: 

Serial Port hangs while closing

This is a known issue with the SerialPort class and described in this Product Feedback article as well as several threads in these forums. You may notice the "closed by design" dismissal.

SwDevMan81
+1, this ties in with the OP's previous question. But for a good SO answer you could have posted short summary **here**. Suppose that that page moves?
Henk Holterman
UNBELIEVABLE!!! this is a known bug in the framework which as closed by MS as "works as designed!!!" +1 for the reference
mfeingold
A: 

It's not a bug.

The only reason it would hang when you close it is because in the event handler of your SerialPort object, you're synchronizing a call with the main thread (typically by calling invoke). SerialPort's close method waits for its EventLoopRunner thread which fires DataReceived/Error/PinChanged events to terminate, but since your own code in the event is also waiting for main thread to respond, you run into a dead lock situation.

The reason the bug report was closed 'as designed' is because the 'bug' is in your own code.

Zach Saw