private void btnCount_Click(object sender, EventArgs e)
{
Thread thread = new Thread(FuncX);
thread.Start();
FuncY();
}
public void FuncX()
{
this.Invoke(new MethodInvoker(delegate
{
//put UI thread code here.
//you can assign local variables values from the main thread in here as well. They are both accessible.
lblThreadDisplayX.Text = "0";
int x = Convert.ToInt32(lblThreadDisplayX.Text);
for (int j = 0; j < loopTime; j++)
{
x++;
lblThreadDisplayX.Text = x.ToString();
Thread.Sleep(5);
Update();
}
}));
}
public void FuncY()
{
lblThreadDisplayY.Text = "0";
int y = Convert.ToInt32(lblThreadDisplayY.Text);
for (int i = 0; i < loopTime; i++)
{
y++;
lblThreadDisplayY.Text = y.ToString();
Thread.Sleep(5);
Update();
}
}
}
}
Above is my code for a tester I'm working on to get threading to work. There are 2 labels, X and Y, which call functions X and Y, and in those functions, the text of the labels are incremented by 1 repeatedly. However, I want to do this simultaneously. When I try to make a thread out of FuncX, it says that it cannot access an object created in another Thread and crashes. I used the lock(){}
statement, but it didn't work. What can I do to have the label's text change inside of a thread?
Edit: Updated the Code, and this is with a Windows Form in Visual Studio 2008. Adding in a Timer to the thread with FuncX in it causes FuncY to execute first, then FuncX's thread.