Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Proper way to close SerialPort with Winforms

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();
    }
like image 588
gdario Avatar asked Nov 08 '09 13:11

gdario


3 Answers

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.

like image 172
SwDevMan81 Avatar answered Nov 13 '22 01:11

SwDevMan81


If your application is calling Invoke to process recevied data try calling BeginInvoke instead.

Instead of:

this.Invoke(d, new object[] { s, tb });

use:

this.BeginInvoke(d, new object[] { s, tb });
like image 22
Mark Dietel Avatar answered Nov 12 '22 23:11

Mark Dietel


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.

like image 10
Zach Saw Avatar answered Nov 12 '22 23:11

Zach Saw