C# Winform freezing on SerialPort.Close

前端 未结 4 1049
闹比i
闹比i 2021-02-06 01:14

I have a winform program that does some asynchronous IO on a SerialPort. However, I\'m periodically running into an issue with the program freezing on the SerialPo

4条回答
  •  孤城傲影
    2021-02-06 01:28

    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

提交回复
热议问题