WPF倒数计时器和DispatchTimer跳过秒

时间:2016-11-29 18:24:51

标签: c# wpf timer

我的代码遇到了一些麻烦。我正在尝试创建一个倒计时器,它会重置每个“x”秒。当计时器达到零时,它执行一些可能需要一些时间的任务。任务完成后,计时器应重新启动并重复此过程。这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;

namespace CamCap
{
    class MainViewModel : ViewModelBase
    {

        private   DispatcherTimer _countDownTimer;

        private DateTime _now;

        private DateTime _next;

        private string _timer;

        private string _timeFound;

        private static int INTERVAL = 5; // interval
        public string Timer
        {
            get { return _timer; }
            set
            {
                _timer = value;
                OnPropertyChanged("Timer");
            }
        }

        public MainViewModel()
        {

            _countDownTimer = new DispatcherTimer();
            _countDownTimer.Tick += async (o, e) => await countdownTimer();
            _countDownTimer.Interval = new TimeSpan(0, 0, 0, 1); // every second
            _countDownTimer.IsEnabled = true;
            _countDownTimer.Start();
            restartCountdown();
        }

        private async Task countdownTimer()
        {

            var timeRemaining = _next - DateTime.Now;
            var t = timeRemaining.Hours + "h " + timeRemaining.Minutes + "m " + timeRemaining.Seconds + "s";
            this.Timer = t;
            var secondsRemaining = (int)timeRemaining.TotalSeconds;

            if (secondsRemaining <= 0)
            {
                _countDownTimer.Stop();
                Console.WriteLine("Executing...");
                await Task.Run(() =>
                {
                    // do  stuff that might take some time
                    validate( );

                });
               _countDownTimer.Start();
            }

        }


        public async void validate( )
        {

            await Task.Run(() =>
            {

            }); 
            // restart timer
            restartCountdown();
        }


        private void restartCountdown()
        {
            _now = DateTime.Now;
            _next = _now.AddSeconds(INTERVAL);
        }

    }
}

此外,倒计时显示在名为Timer的标签上。我面临的问题是,当倒计时重新开始时,一些秒被跳过并且不会显示中间秒。例如:从9秒开始,它将显示6秒但不会显示8或7。

我认为它与async / await如何工作有关,因为DispatchTimer是在主线程中启动的。我不知道如何解决这个问题。

0 个答案:

没有答案