Cross threading
Posted: Fri Oct 28, 2022 2:50 pm
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();
}
}
}
"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();
}
}
}