1

I have this event that is running every minute.

void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
{
    if (DateTime.Now.Hour == 10 && DateTime.Now.Minute == 35)
    {
        tik_tak();
    }
}

And at a specific time, in my case 10:35 I want to display a countdown timer in a label (I already have)

    private void tik_tak()
    {
        EndOfTime = DateTime.Now.AddMinutes(10);
        System.Windows.Forms.Timer t = new System.Windows.Forms.Timer() { Interval = 500, Enabled = true };
        t.Tick += new EventHandler(t_Tick);
        t_Tick(null, null);
    }

    void t_Tick(object sender, EventArgs e)
    {
        TimeSpan ts = EndOfTime.Subtract(DateTime.Now);
        label1.Text = ts.ToString();
    }

And now I am getting "Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on"

How can I manage to do this?

bags
  • 67
  • 5
  • 2
    Does this answer your question? [Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on](https://stackoverflow.com/questions/12618575/cross-thread-operation-not-valid-control-label1-accessed-from-a-thread-other) – Lance U. Matthews Nov 25 '21 at 09:19

1 Answers1

3

You can't modify your GUI elements from another thread. For do this you need to instruct your dispacther to execute this line of code label1.Text = ts.ToString(); on its thread.

It is done in this way

label1.BeginInvoke((MethodInvoker)delegate ()
            {
                label1.Text = ts.ToString();
            });
Stefano Cavion
  • 641
  • 8
  • 16