Page 1 of 1

Cross threading

Posted: Fri Oct 28, 2022 2:50 pm
by ProtonTim
I have a very simple C# single form program that opens an accelerometer and attaches event handler. When the event happens I try to write to a text box that is part of the form, but I get a message saying:
"System.InvalidOperationException: 'Cross-thread operation not valid: Control 'AccelX' accessed from a thread other than the thread it was created on.'"

The textbox AccelX is created as part of class Form1. I don't understand why that is on a different thread (since it is part of the same form) or how to overcome this issue.

Here is the Phidget code: Thanks in advance

namespace Accelerometers
{
public partial class Form1 : Form
{
//private Accelerometer accelerometer0;

public Form1()
{
InitializeComponent();
InstallPhidgets();
}

public void InstallPhidgets()
{
Accelerometer accelerometer0 = new Accelerometer();
accelerometer0.AccelerationChange += Accelerometer0_AccelerationChange;
accelerometer0.Open(5000);
}

public void Accelerometer0_AccelerationChange(object sender, Phidget22.Events.AccelerometerAccelerationChangeEventArgs e)
{
AccelX.Text = e.Acceleration[0].ToString();
}
}
}

Re: Cross threading

Posted: Fri Oct 28, 2022 8:34 pm
by cvboucher
You're trying to update the UI from a non-UI thread. You need to call Invoke.

https://stackoverflow.com/questions/661 ... her-thread

Craig

Re: Cross threading

Posted: Sat Oct 29, 2022 12:34 pm
by ProtonTim
Thank you very much. The following code seems to do the trick.
public void Accelerometer0_AccelerationChange(object sender, Phidget22.Events.AccelerometerAccelerationChangeEventArgs e)
{
Invoke((MethodInvoker)delegate {
// Running on the UI thread
AccelX.Text = e.Acceleration[0].ToString();
});
}