DispatcherTimer用于显示秒数

cre*_*ive 1 wpf windows-mobile windows-phone-7

我想显示一个简单的第二个计数器.我有一个调度时间间隔为1秒的调度程序和一个文本框,我在tick处理程序中用当前的秒数更新.tick处理程序中有很少的工作,即在某些int上调用'tostring()'.

我的问题是秒数比它们应该慢.即使我将间隔设置为100毫秒并在经过时进行检查,它仍然比它应该更慢.(在一分钟内它大约慢了6秒).

有人能指出我正确的方向显示准确的第二个计数器吗?

编辑:这里的一些代码(在.xaml.cs中).它取自一个工作正常的例子.不同之处在于我设置了TextBox的Text属性,而不是另一个控件的Value属性.

...
        this.timer.Interval = TimeSpan.FromMilliseconds(100);
...

    private void OnDispatcherTimer_Tick(object sender, EventArgs e) {
        if (this.currentValue > TimeSpan.Zero) {
            this.currentValue = this.currentValue.Value.Subtract(TimeSpan.FromMilliseconds(100));
        } else {
            // stop timer etc
        }

        this.seconds.Text = this.currentValue.Value.Seconds.ToString();
    }
Run Code Online (Sandbox Code Playgroud)

Kev*_*sse 7

你跟踪时间的方式是有缺陷的.每次计时器滴答时,您都在递增一个计数器,但不能保证您的计时器每100毫秒执行一次.即使它确实如此,您也必须考虑代码的执行时间.因此,无论你做什么,你的计数器都会漂移.

你必须做的是存储你开始计数器的日期.然后,每次计时器滴答时,您计算已经过的秒数:

private DateTime TimerStart { get; set; }

private void SomePlaceInYourCode()
{
    this.TimerStart = DateTime.Now;
    // Create and start the DispatcherTimer
}    

private void OnDispatcherTimer_Tick(object sender, EventArgs e) {
    var currentValue = DateTime.Now - this.TimerStart;

    this.seconds.Text = currentValue.Seconds.ToString();
}
Run Code Online (Sandbox Code Playgroud)