Passing variables from a thread to another form using C#
- by kirstom14
Hi,
I am trying to pass 2 variables from a thread, in the MainForm, to another form, but when doing so an error occurs.
private void TrackingThread( )
{
float targetX = 0;
float targetY = 0;
while ( true )
{
camera1Acquired.WaitOne( );
camera2Acquired.WaitOne( );
lock ( this )
{
// stop the thread if it was signaled
if ( ( x1 == -1 ) && ( y1 == -1 ) && ( x2 == -1 ) && ( y2 == -1 ) )
{
break;
}
// get middle point
targetX = ( x1 + x2 ) / 2;
targetY = ( y1 + y2 ) / 2;
}
if (directionForm != null)
{
directionForm.RunMotors(targetX, targetY);
}
}
}
In the form, directionForm, I am simply displaying the variables targetX and targetY.
The code for the directionForm.RunMotors() is the following:
public void RunMotors(float x, float y)
{
label1.Text = "X-ordinate " + x.ToString();
label2.Text = "Y-ordinate " + y.ToString();
}
The error happen when I am trying to display the two variables:
"InvalidOperationException was unhandled
Cross-threading operation not valid: Control label1 accessed from a thread other than . the thread it was created on"
What shall I do???
Thanks in advance