C# Winform freezing on SerialPort.Close

The 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.

solution: use begininvoke instead of invoke: https://connect.microsoft.com/VisualStudio/feedback/details/202137/serialport-close-hangs-the-application

reference: http://stackoverflow.com/a/3176959/146622

EDIT: the Microsoft link is broken as they have retired Connect. try web.archive.org: https://web.archive.org/web/20111210024101/https://connect.microsoft.com/VisualStudio/feedback/details/202137/serialport-close-hangs-the-application


I had a same problem. I solved this problem by using SerialPortStrem library. You can install by Nuget Pageckage Installer.

SerialportStream libary has the following advantages.

  • An independent implementation of System.IO.Ports.SerialPort and SerialStream for better reliability and maintainability.

After using SerialPortStream library, I hadn't UI freezing problem such as deadlock in WPF. I think the same issue in Windows forms. so, use the SerialPortStream library.

This library is obviously a solution to solve the UI Freezing.