How do I update the user interface from C # events triggered by serial port data?

I am a technical level employee who helps with coding in a test production environment. The specific issue is event handling in C #. Not just Button_click, especially if I have a stream of data coming in through the serial port and you need to update the interface in real time according to what comes in through the serial port. For example, if I have two approaches that end up doing 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 convention a more complex second approach, can I avoid using the first approach around the world when real-time performance is important?

+7
c # callback events
source share
1 answer

If I understand: The first approach is to always call a call to update the interface. The second approach is if InvokeRequired returns true call invoke else - just create user interface stuff

Now, if we know that a handle has been created for management, and we only want to make small and quick updates to the user interface, we can use the first approach, and the user interface will be responsible, but with Invoke locking is still possible. If we do not want the control to be created now for the control, we must call IsHandleCreated to make sure Invoke will succeed and not throw an exception. If IsHandleCreated returns false, we cannot update through Invoke, and we must wait for the descriptor to be created.

The second approach is worse, because field.InvokeRequired can return false if the handle to control is not created, and when we call field.Text = d; A control descriptor can be created on the background thread, isolating the flow control without a message pump and making the application unstable.

So for me this is the best way:

 private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { input = (sender as SerialPort).ReadLine(); if (input.Contains("look for this")) { if (this.IsHandleCreated == false) { //do some stuff to proper handle creation or just wait for handle creation } this.BeginInvoke(new EventHandler(doSomething)); } } 
+1
source share

All Articles