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