What causes my UI to freeze when closing a serial port?

前端 未结 2 835
庸人自扰
庸人自扰 2021-01-15 03:17

I am working on a serial port related application. While using DataReceived event of SerialPort I need to update a textbox with the received bytes:

2条回答
  •  悲哀的现实
    2021-01-15 03:47

    Yes, this code has very high odds of causing deadlock on the Close() call. The serial port cannot close until the DataReceived event handler stops running. But the Invoke() call cannot complete until the UI thread goes idle and pumps the message loop. It isn't idle, it is stuck in the Close() call. So the event handler cannot make progress because it is stuck in the Invoke() call and your main thread cannot make progress because it is stuck in the Close() call, deadlock city.

    The best workaround is to use BeginInvoke() instead, that doesn't block the event handler. Not closing the serial port at all is another workaround, which is okay since Windows takes care of it automatically when your program terminates. In general, closing a serial port while the device is busy sending data is iffy and inevitably causes data loss. Okay when you're debugging your code but not something you'd normally like to see happening in production.

提交回复
热议问题