What am I doing wrong here?
my plan is to change the label text property from a different thread without getting the “Cross-thread operation not valid” exception.
private void button1_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(new ThreadStart(ChangeTime));
thread1.Start();
}
delegate void SetTimeDelegate();
private void ChangeTime()
{
while (true)
{
if (lbl1.InvokeRequired)
{
SetTimeDelegate setTime = new SetTimeDelegate(ChangeTime);
lbl1.Invoke(setTime);
}
else
{
lbl1.Text = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt");
Thread.Sleep(1000);
}
}
}
To update a UI control from a different thread you need to call the
BeginInvokeorInvokemethod. You can use the specific control’s methods or the form’s.Your original code has infinite recursion. You are Invoking correctly except your delegate is calling the same method. Create a separate method for updating the label with the time and have the delegate cll that new method.
I also added a field on the form to exit the loop when the form is closing or else weird things happen.
My original code: