Countdown Timer in a strip status label c#

c#, countdown, timer, winforms

Solution

Instead of blocking thread execution, simply call your method when required timeout passes. Place new `Timer` to your form, and set it's Interval to `1000`. Then subscribe to timer's `Tick` event and calculate elapsed time in event handler:

private int secondsToWait = 42;
private DateTime startTime;

private void button_Click(object sender, EventArgs e)
{
    timer.Start(); // start timer (you can do it on form load, if you need)
    startTime = DateTime.Now; // and remember start time
}

private void timer_Tick(object sender, EventArgs e)
{
    int elapsedSeconds = (int)(DateTime.Now - startTime).TotalSeconds;
    int remainingSeconds = secondsToWait - elapsedSeconds;

    if (remainingSeconds <= 0)
    {
        // run your function
        timer.Stop();
    }

    toolStripStatusLabel.Text = 
        String.Format("{0} seconds remaining...", remainingSeconds);
}

Problem

My program has a parameter that starts up the winform and waits x number of seconds before it runs a function. Currently I am using Thread Sleep for x seconds and then the function runs. how can I add a timer in the strip status label? so that it says: `x Seconds Remaining...`

Original source