I'm a tech-level employee helping out with some of the coding in a manufacturing test environment. The specific question is handling events in C#. Not just Button_click, specifically if I have a stream of data coming through a serial port and have to update the UI in real time according to what is coming in through the serial port. For example, if I have two approaches that both ultimately do the same thing, what is the difference between:
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) {
input = (sender as SerialPort).ReadLine();
if (input.Contains("look for this"))
this.Invoke(new EventHandler(doSomething));
}
And something like:
void OnGotData(object sender, EventArgs e) {...};
delegate void UpdateCallback(data d);
void doSomething(data d) {
...
if (field.InvokeRequired) {
UpdateCallback x = doSomething;
this.Invoke(x, new object[] { d });
}
else {
field.Text = d;
}
...
}
What are the tradeoffs? Is the more convoluted second approach a matter of convention, Could I get away with using the first approach everywhere when real-time performance is important?
If i understand: First approach - always call invoke to update UI Second approach - if InvokeRequired returns true call invoke else - just do UI stuff
Now, if we know that handle for control was created and we want just made small and fast UI updates we can use first approach and UI will be responsible, but with Invoke deadlock is still possible. Than if we don't now if the handle for control is created we must call IsHandleCreated to ensure that Invoke will be successfull and will not throw exception. If IsHandleCreated returns false we cannot update via Invoke and we must wait for handle to be created.
Second approach is worse, because field.InvokeRequired may return false if handle for control is not created and when we call
field.Text = d;
the control's handle may be created on the background thread, isolating the control on a thread without a message pump and making the application unstable.So as for me this is the better way: