Cross threading

Supporting Visual Studio on Windows
Post Reply
ProtonTim
Phidgetly
Posts: 17
Joined: Wed Feb 24, 2021 3:02 pm
Contact:

Cross threading

Post 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();
}
}
}
cvboucher
Phidgetsian
Posts: 13
Joined: Fri Oct 22, 2021 11:29 am
Contact:

Re: Cross threading

Post 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
ProtonTim
Phidgetly
Posts: 17
Joined: Wed Feb 24, 2021 3:02 pm
Contact:

Re: Cross threading

Post 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();
});
}
Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests