简体   繁体   中英

How To keep the Countdown timer ticking

I am working on an app were i am using a countdown timer,my problem is that after every minute the timer stops and if i close or open the App again it ticks again and stops after one minute. the code for the timer is

 TimeSpan span2 = TimeSpan.FromSeconds(1);
    TimeSpan span;
    private void tbkRemaningTime_Loaded(object sender, RoutedEventArgs e)
    {
        TextBox text = sender as TextBox;
        TimeSpan.TryParse(text.Text, out span);


                if (span.Seconds > 0)
                {
                    span = span.Subtract(span2);
                    text.Text = span.ToString();
                }



    }

    private async void tbkRemaningTime_TextChanged(object sender, TextChangedEventArgs e)
    {
        await System.Threading.Tasks.Task.Delay(1000);
        TextBox text = sender as TextBox;
        TimeSpan.TryParse(text.Text, out span);

        if (span.Seconds > 0)
        {
            span = span.Subtract(span2);
            text.Text = span.ToString();
        }

Use the System.Threading.Timer:

TimerCallback oneMinuteElapsed = new TimerCallback(TimerHandler);
Timer timer1;
timer1 = new Timer(oneMinuteElapsed, "min1", 0, 1000*60);

private static void TimerHandler(object state)
{
      ...
}

The Ticker timer1 starts oneMinuteElapsed every minute and that calls the TimerHandler where you can put your code that shall be performed every minute.

the last parameter of Timer is the delay in millisecounds. the parameter before this (here 0) defines when to start the ticking.

TimeSpan.Seconds returns only the seconds portion of the TimeSpan - a value from -59 to 59. You probably want to use TotalSeconds instead.

IOW, this code (in two places)

if (span.Seconds > 0)
{
    span = span.Subtract(span2);
    text.Text = span.ToString();
}

is going to stop doing anything after about 1 minute, because span.Seconds will be 0, even though span represents a much longer length of time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM