Home > Mobile >  Start countdown at a specific time and show it in a label
Start countdown at a specific time and show it in a label

Time:11-25

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?

CodePudding user response:

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();
            });
  • Related