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:
private void Connection_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
ledReceive.On = true;
var data = Connection.ReadExisting();
_readBuffer.Add(data);
Invoke(new EventHandler(AddReceivedPacketToTextBox));
}
So I use Invoke to update the textbox. But there is a big problem. When I try to close connection, my UI gets freezed, I think this is becase Invoke is doing somehing perhaps.
A friend said I should use RequiredInvoke, but I have no idea what he ment really. How can I close the connection without messing up the invoke and UI thread?
Here is my close method:
private void DisconnectFromSerialPort()
{
if (Connection != null && Connection.IsOpen)
{
Connection.Close();
_receivedPackets = 0; //reset received packet count
}
}
I’m not fully sure, but I would guess that the thread that is updating your UI is removed when you close your connection, which could explain why it freeze. But I can’t be sure without digging in all your code.
InvokeRequired return true if the thread trying to access your element isn’t native to your UI. Or if you prefer MS explaination:
And a basic implementation:
The Invoke should be the first thing your function does, to prevent that thread from entering deep in your UI. Now, if the connection itself is determined to be within the bounderies of your UI’s thread, it probably won’t trigger “InvokeRequired”. One way to prevent this from happening, would be to manually create a thread that update your UI that isn’t bound to your connection.
I had a similar problem with a clock updating the rendering of multiple UI element. The clock would work fine, but would “hang” until all the UI is done rendering, which in case of a lot of UI would mean it would skip it’s next tick.
This way, my clock (or your connection) would start an independant thread that does its stuff on its own. You may also want to check the Monitor class or the lock keyword to prevent colliding threads or multiple threads using the same variables.
EDIT: Or you could read the awesome answer at, which probably make more sense than mine: What causes my UI to freeze when closing a serial port?